dimanche 30 septembre 2018

Table List with Two Column

I need some help to create two column table list like this but for the left column I need to do a checkbox which can select the resources.

How can I create two column table list something like this ?




Android: Dynamic number of CheckBoxes for each Row in a ListView

My app shows a listview with a textview and checkbox for each row. The textview contains different types of food. Each row has one checkbox. I want to change that. Each type of food has an attribute called "numberOfPortions“. This number should determine the number of checkboxes in the row. For example: ListItem Beans numberOfPortions = 3 This means that the row in my listview with beans should have 3 checkboxes instead of previously 1 checkbox. How can I achieve that? If I add three checkboxes to my row layout, three checkboxes will be shown in each row, but there are also rows were numberOfPortions is 1 or 2 so that only one or two checkboxes should be shown.

This image shows how my list should look like: https://i.stack.imgur.com/GxV0k.png




Filed values changes unexpectedly using checkbox

I have multiple checkbox and their field name but i dont know where i have done wrong the name of the field changes i am unable to find out where is the problem.

Here my screen shot when checkbox values were fine:here is fine fields working good

And this here is screen shot there is multiple questions marks like ???? and these becoming annoying this fields value are with ???? there should not any question marks in this field

And my form where these checkboxes value are:

                  <form id="preferences_form" role="form" method="POST" novalidate action="" class="mujucet-registration">
                            
                            <h5>Nastavení zpráv</h5>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="checkbox">
                                        <label  for="ch1">
                                            <input type="checkbox" name="monthly" value="1" id="ch1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Mesícní výpisy
                                        </label>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="checkbox">
                                        <label >
                                            <input type="checkbox" name="weekly" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Týdenní prehled
                                        </label>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="tax_reviews" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Danové výpisy
                                        </label>
                                    </div>
                                </div>

                                <div class="col-md-4">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="quarterly" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Ctvrtletní výpisy
                                        </label>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="annually" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Rocní výpisy
                                        </label>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="newsletter" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Novinky
                                        </label>
                                    </div>
                                </div>

                                <div class="col-md-12">
                                    <div class="checkbox">
                                        <label class="border">
                                            <input type="checkbox" name="direct_mail_reviews" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span> Chci výpisy zasílat také Poštou <span class="light">20 kc za výpis</span>
                                        </label>
                                    </div>
                                </div>

                            </div><h5>Kontaktní preference</h5>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="email" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Email
                                        </label>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="sms" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>SMS
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </form>                    </div>

I dont how my checkboxes value goes weird here your help will be highly appreciated!




Only one checkbox appears in the CheckedTextView

I'm trying to use multiple checkboxes through a listView. But only the first checkbox connected to the first element of the array appears to me. The Class:

        ArrayList<String> selectedItems = new ArrayList<>();
        ListView lvCheckboxList;

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

        lvCheckboxList = (ListView) findViewById(R.id.lvCheckboxList);
        lvCheckboxList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

                    String[]  stringa = {"a","b","c"};
                    ArrayAdapter<String> adapterName = new ArrayAdapter<String>(SingleSiteActivity.this, R.layout.check_list, R.id.checkboxList, stringa);
                    lvCheckboxList.setAdapter(adapterName);

                    lvCheckboxList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            String selectedItem = ((TextView)view).getText().toString();
                            if (selectedItems.contains(selectedItem)){
                                selectedItems.remove(selectedItem);
                            } else {
                                selectedItems.add(selectedItem);
                            }
                        }
                    });

The xml file where there is the CheckedTextView consists of these few lines:

    <?xml version="1.0" encoding="utf-8"?>
        <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/checkboxList"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:gravity="center_vertical"
        android:checkMark="?android:attr/listChoiceIndicatorMultiple"
        android:padding="5dp"/>

While the main xml file containing the ListView is this:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.XXXXXXXX">







                <ListView
                    android:id="@+id/lvCheckboxList"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                </ListView>



                <Button
                    android:id="@+id/bSelection"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="SELEZIONA"/>


</android.support.constraint.ConstraintLayout>




Need to get the values of the checked checkboxes in Webgrid

As the title says. I am having trouble on accessing the checkbox on webgrid.

My Webgrid

<div id="grid" >
        @grid.Table(
        tableStyle: "table table-responsive table-bordered",
            columns: grid.Columns(
                grid.Column(format:@<text> <input type="checkbox" value="Check_@item.SubjectCode" name="ids" /></text>, header: "Check"),
                grid.Column(columnName: "SubjectCode", header: "SubjectCode"),
                grid.Column(columnName: "SubjectName", header: "SubjectName"),
                grid.Column(columnName: "SubjectDescription", header: "SubjectDescription"),
                grid.Column(columnName: "Units", header: "Units"),
                grid.Column(columnName: "Schedule", header: "Schedule"),
                grid.Column(columnName: "Instructor", header: "Instructor"),
                grid.Column(columnName: "Room", header: "Room")
            )

        )
        <div class="row">
            <div class="col-md-6">
                @grid.PagerList(mode: WebGridPagerModes.All, paginationStyle: "pagination pagination-small pagination-right")
            </div>
        </div>

        @Html.Hidden("dir", grid.SortDirection)
        @Html.Hidden("col", grid.SortColumn)

        <div class="col-md-1">
            <a class="btn btn-success btn-block" id="subjectSave" >Save</a>
        </div>
        <div class="col-md-1">
            <a class="btn btn-success btn-block" href="~/Account/Home">Back</a>
        </div>

    </div> 
</div>

My Jquery

<script>
    $('#subjectSave').click(function mySave(e) {
        var arrItem = [];
        var commaSeparatedIds = "";
        $("#grid  input[type=checkbox]").each(function (index, val){
            debugger
        })

    })
</script>

I'm having trouble on what to put in

$("#grid input[type=checkbox]").each(function (index, val){

I only saw a code for "li" and none for webgrid. I need to get all the values of the checked checkbox put it in array and send it to the controller so I can queried each of it.

I hope someone can help me. Im still studying java so I'm not yet familiar of other kind of things. Thank you in advance




samedi 29 septembre 2018

Disabled checkbox if the value is in database

Hello guys can help me? about how I disabled a checkbox if the value of checkbox is already in database I have inserted value of 1A,1B in database, but suddenly all the checkbox is disabled :( here's my simple code

 <?php
    //Connections
$server_name='localhost';
$username='root';
$password='admin';
$db_name='matnogreservationv2';
$con= mysqli_connect($server_name, $username, $password, $db_name);
if(mysqli_connect_errno())
{
    echo 'Failed..!!'.mysqli_connect_errno();
} 
>?


//code for disabling checkbox
$resulta= mysqli_query($con,"SELECT * FROM seat WHERE SeatStatus = 1");
$display = mysqli_num_rows($resulta);
$con->query($display);
$disable = $display ? 'disabled="disabled"': '';

<input type="checkbox" name="seat[]" id="1A" value="1A"  <?php echo $disable; ?>>
          <label for="1A">1A</label>

          <input type="checkbox" name="seat[]" id="1B" value="1B" <?php echo $disable; ?>>
          <label for="1B">1B</label>

          <input type="checkbox" name="seat[]" id="1C" value="1C"<?php echo $disable; ?>>
          <label for="1C">1C</label>

          <input type="checkbox" name="seat[]"  id="1D" value="1D"<?php echo $disable; ?>>
          <label for="1D">ID</label>

          <input type="checkbox" name="seat[]" id="1E" value="1E"<?php echo $disable; ?>>
          <label for="1E">1E</label>

          <input type="checkbox" name="seat[]" id="1F" value="1F"<?php echo $disable; ?>>
          <label for="1F">1F</label>

enter image description here




JQuery input type checkbox prop("checked", false/true) does the opposite


 I have an HTML checkbox element, with a Label element linked to it by the "for" attribute of Label, I tried to check/uncheck the checkbox element by capturing the click event of the Label element,
Can somebody tell why this code does the opposite of what is intended,

$("label").click(function() {

  $(this).toggleClass("active");

  if ($(this).hasClass("active")) {

    $("#checker").prop("checked", true);
    console.log("checked");
    
  } 
  
  else {
    
    $("#checker").prop("checked", false);
    console.log("unchecked");

  }

});
.active {
  background: green;
  color: white
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for='checker'>Check it</label>
<input type='checkbox' id='checker'>

Whereas this code works just fine.

$("label").click(function(){
                
                $(this).toggleClass("active");
                
                if($(this).hasClass("active")){
                
                        setTimeout(function(){
                                $("#checker").prop("checked",true);
                        },0);
                        console.log("checked");
      
                }
                                        
                else{

                        setTimeout(function(){
                                $("#checker").prop("checked",false);
                        },0);
      console.log("unchecked");
                        
                }
                        
});
.active {
  background: green;
  color: white
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for='checker'>Check it</label>
<input type='checkbox' id='checker'>



my checkbox doest not match the count of data

I made checkbox the data from database and still work, when I click multiple checkbox, the count of data clicked is matches

result console.log enter image description here

the problem when I sending data to filter.php with method post

the count of data received is not matches enter image description here event click jquery

$(document).ready(function() {
                $('#t_pendaftar').DataTable();
                    $('#filter').click(function () {
                     var data = { 'venue[]' : []};
                     var arr = $('.treas:checked').map(function () {
                        data['venue[]'].push($(this).val());
                     }).get();
                     console.log(data);
                     $.post("filter.php",{data : data});
                 });       
                });

filter.php

<?php var_dump($_POST['data']);   if(!empty($_POST['data'])) {
    foreach($_POST['data'] as $check) {
            print_r($check);
     } }   ?>

thank you for attention




form with two checkbox assigns different links to a button

I'm trying to insert a form in a page (wordpress) that shows two checkbox options and depending of what option is selected, a link is assigned to a button.

thanks

enter image description here




vendredi 28 septembre 2018

GPA that updates when an item in the Listbox is Removed

I've created a listbox that displays a checked grade and selected credit plus is respective GPA. Each row of listbox items calculates the cumulative GPA. For instance, the listbox shows:

  1. A - 1 4.000
  2. C - 1 3.000
  3. D - 3 1.800

If I remove the last item, the cumulative GPA will be 3.000. However, if I remove the 2nd item, the GPA should be 2.500. However, it isn't how it should be when I tested my code.

These are the codes that I used:

//global declarations
List<double> allGrades = new List<double>();
        List<double> allHours = new List<double>();
        List<double> allGPA = new List<double>();
        List<int> gradeValue = new List<int>();
        private RadioButton currentRadioButton;
        Dictionary<char, double> gradeValuesMap;

        public string StudentName { get; set; }

 public DataEntry()//switch back to pass value: string input
        {
            InitializeComponent();
            gradeValuesMap = new Dictionary<char, double>();
            gradeValuesMap.Add('A', 4.0);
            gradeValuesMap.Add('B', 3.0);
            gradeValuesMap.Add('C', 2.0);
            gradeValuesMap.Add('D', 1.0);
            gradeValuesMap.Add('F', 0.0);            
        }


    enter code here

   private void btnEnter_Click(object sender, EventArgs e)
            {
                /*if grades and credits are not selected, Error Message:
                    * MessageBox.Show("A grade must be selected.");
                    * MessageBox.Show("Credit hours must be selected.");
                */
                if (!(radA.Checked || radB.Checked || radC.Checked ||
                    radD.Checked || radF.Checked))
                {
                    MessageBox.Show("A grade must be selected.");
                }

                if (cboCreditHrs.SelectedIndex == -1)//if" no credit is selected
                {
                    MessageBox.Show("Credit hours must be selected.");
                }
                else
                {
                    // do gpa math here
                    // sum(grades * credits) / sum(credits)


              var grade = getGradeValue(currentRadioButton.Text);
              var credit = Convert.ToDouble(cboCreditHrs.SelectedItem.ToString());


                    // sum(4 * 4) / sum(4)
                    var result = (grade * credit) / credit; //GPA calculation

                    allGrades.Add(grade);
                    allHours.Add(credit);

                    double sum = 0;

                    for (int i = 0; i < allGrades.Count; i++)
                    {
                        sum += allGrades[i] * allHours[i];
                    }


                    result = (sum)/ allHours.Sum();

                    string listboxItem = string.Format("{0}-{1} {2}", currentRadioButton.Text, cboCreditHrs.SelectedItem, result.ToString("n3"));
                    lstDetail.Items.Add(listboxItem);

                    // uncheck the currently checked radio button
                    currentRadioButton.Checked = false;

                    // reset the combox selection
                    cboCreditHrs.SelectedIndex = -1;
                }
            }

To remove the selected item. I used the following Even Handler:



     private void btnRmvSelect_Click(object sender, EventArgs e)
        {
            ///*foreach (DataEntry i in lstDetail.*/SelectedItems)
                //lstDetail.Items.Remove(i);

            for (int i = 0; i < lstDetail.SelectedItems.Count; i++)
                lstDetailhttps://stackoverflow.com/questions/20277193/how-to-change-the-selecteditem-foreground-text-of-listbox-item.Items.Remove(lstDetail.SelectedItems[i]);

        }

Most likely, my code above is missing something. Thus why the expected result is incorrect. Can anyone correct my code?




Android uncheck select all checkbox on Recycler item uncheck

I have recycler view items with Checkbox component and implemented common "Check All" button. When I "uncheck" the button in list item, I want to "uncheck" common "Select All" Checkbox outside the recycler view.

I having issue in accessing the common "Select All" Checkbox in Adapter.

In my adapter class added below code,

private class UserViewHolder extends RecyclerView.ViewHolder {
    public TextView title;
    public CheckBox commonCheckbox, itemCheckbox;
    public UserViewHolder(View view) {
        super(view);
        itemCheckbox=view.findViewById(R.id.itemcheckbox);
        title=view.findViewById(R.id.title);
        commonCheckbox = view.findViewById(R.id.commoncheckbox);
    }
}

In onBindViewHolder, I implemented the following checked listener,

userViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                userViewHolder.commonCheckbox.setChecked(false);
            }
        }
    });

But, commonCheckbox showing null pointer exception. Thanks in advance.




How to create if and else for the checkbox

<div id="htm_years" class=""><p><input type="checkbox" value="1892_62500"><span>1892-62500 </span></p><p><input type="checkbox" value="1915_62500"> </div>

Please the above html code




OnCheckedChanged event returns Check Box always as unchecked

I am trying to work in a VB project, but since is my first experience in VB i am having some kind of difficulties. I a have a check Box and a text box. I want that if the user checks the check box the text box to enable.

 <tr>
 <td></td>
 <td style="width:100px; ">Staff:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp                                                                          

  <asp:CheckBox ID="CheckBox3" runat="server" AutoPostBack="True" 
      OnCheckedChanged="CheckBox3_CheckedChanged" />
 </td>
 <td style="width:200px; ">

 <edititemtemplate>

 <telerik:RadTextBox ID="RadTextBox2" width="100%" Runat="server" 
     Enabled="false">

 </telerik:RadTextBox>

</edititemtemplate>
</td>  
   <td class="Validator_Cls"></td>                                                                  
   </tr>

and this is the code behind

Dim RadTextBox2 As New TextBox
Dim WithEvents CheckBox3 As New CheckBox

    Public Sub CheckBox3_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox3.CheckedChanged
    If CheckBox3.Checked = True Then
        RadTextBox2.Enabled = True
    End If

End Sub

the thing is that even when i check the check box the if clause says that check box is not checked and does not enter in the if statement.

Any idea where i am doing wrong? Please help because this is taking longer than it should.




APEX 5 How to write selected Checkbox for each value in separated rows?

i have a Checkbox Item in my Apex Form which gets everything from a LOV. There is

1 2 3 4 5

source is my Database Column.

If i submit this form Apex writes me for example
ID:1 Checkbox_value: 2:3:5
in my table.

But i need it in separated rows. Like:
ID: 1 Checkbox_value: 2
ID: 1 Checkbox_value: 3
ID: 1 Checkbox_value: 5

I did not find any options at the Checkbox item. Can someone help me with a Idea?

Thanks a lot :)




jeudi 27 septembre 2018

Custom tick mark in a custom checkobx is not displaying

I have a custom checkbox which I want to add a tick mark inside it when checked

Here is HTML I have:

  <p class="checkbox">
                                <input type="checkbox" class="checkbox  checkbox-custom" name="cgv" id="cgv" value="1" {if $checkedTOS}checked="checked"{/if} />
                                <label class="checkbox-custom-label" for="cgv">{l s='I agree to the terms of service' mod='threepagecheckout'}</label>
                                <a href="{$link_conditions|escape:'html':'UTF-8'}" class="iframe" rel="nofollow">{l s='(Read the Terms of Service)' mod='threepagecheckout'}</a>
                            </p>

Here is css;

input[type="checkbox"] {
    transform: scale(3, 3) !important;
    margin: 0px 21px;
}

.checkbox-custom,
.checkbox-custom-label {
    display: inline-block;
    vertical-align: middle;
    margin: 5px 7px;
    cursor: pointer;
    font-size: 2.4rem;
    font-family: "FuturaPT_BOOK";
    /* padding: 6px; */
}
[type="checkbox"]:not(:checked)+label:after,
[type="checkbox"]:checked+label:after {
  content: '✔';
  position: absolute;
  top: 8px;
  left: 10px;
  font-size: 24px;
  line-height: 0.8;
  color: #fff;
  transition: all .2s;
}

.checkbox-custom+.checkbox-custom-label:before {
    content: '';
    background: #fff;
    border: 1px solid #000;
    display: inline-block;
    vertical-align: middle;
    width: 30px;
    height: 30px;
    padding: 2px;
    margin-right: 30px;
    text-align: center;
    border-radius: 24%;
}

.checkbox-custom:checked+.checkbox-custom-label:before {
    background: #0000;
    box-shadow: inset 0px 0px 0px 4px #fff;
}

unfortunately when I click on check box nothing is displayed, I have tried different combination but nothing worked,

what am I doing wrong?




Facebook API {"error":{"message":"(#100) No matching user found","type":"OAuthException" Checkbox Plugin

I am trying to use the feature of checkbox plugin. I manage to make the checkbox rendered. A few days ago, I managed to send some basic text 'Hello World' to the user. But now I'm not able to send anything thing. Whenever I tried to send to the user I get this error:

{"error":{"message":"(#100) No matching user found","type":"OAuthException","code":100,"error_subcode":2018001,"fbtrace_id":"HCZPBkofiz9"}}

I even try to cURL using, but no success, still the same error.

curl -X POST -H "Content-Type: application/json" -d '{
  "recipient": {
      "user_ref":"<UNIQUE_REF_PARAM>"
  }, 
  "message": {
      "text":"hello, world!"
  }
}' "https://graph.facebook.com/v2.6/me/messages?access_token=<PAGE_ACCESS_TOKEN>" 

What I've done are:

  1. Uninstalled app from page.
  2. Select the page again and generate new PAGE_ACCESS_TOKEN.
  3. Subscribe to messages, messaging_postbacks, messaging_optins webhooks to the page.
  4. Set the new token in .env.
  5. Save up the new user_ref through checkbox plugin.
  6. Try cURL by using the new user_ref, no luck.

I am able to send with recipient senderID but not user_ref for checkbox plugin.

Any help, are very much appreciated :)




Why does this delete every other checkbox?

Rank noob again learning C# with Winforms. I was practicing adding checkboxes to a panel, and then removing them. The "start_button" button adds checkboxes. This works. The "remove_button" button is supposed to delete all of them. But it doesn't. By playing around with the # of checkboxes, I figured out that it removes every other checkbox. Another click and it removes every other of the remaining ones, and so on until they are all gone.

Why?

Thanks, Aram

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace playingWithPanels
{
public partial class Form1 : Form
{
    CheckBox chkBox;
    TextBox txtBox;
    public Form1()
    {
        InitializeComponent();
    }


    private void start_button_Click(object sender, EventArgs e)
    {
        txtBox = new TextBox();
        txtBox.BringToFront();
        txtBox.Text = "Textbox";
        txtBox.Location = new Point(30, 10);
        panel1.Controls.Add(txtBox);
        for (int i =0;i<20;i++)
        {
        chkBox = new CheckBox();
        chkBox.BringToFront();
        chkBox.Text = "Checkbox_" + i.ToString();
        chkBox.Name = "Checkbox_" + i.ToString();
            chkBox.AutoSize = true;
        chkBox.Location = new Point(30, 40 + 25 * i);
        panel1.Controls.Add(chkBox);
        }
    }

    private void remove_button_Click(object sender, EventArgs e)
    {
        foreach (var ctrl in panel1.Controls.OfType<CheckBox>())
        {
            panel1.Controls.Remove(ctrl);
        }
    }
}
}




How to check all checkbox in datagrid when the checkbox in header column are checked during runtime?

This is my XAML code

  <DataGrid x:Name="missiongrid" >
     <DataGrid.Columns>

                    <DataGridTemplateColumn  Header="Mission type" Width="320">
                        <DataGridTemplateColumn.HeaderTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <CheckBox x:Name="UpCheckbox"  Margin="10,10,0,0" 
                                               Content="Name"
                                               Checked="UpCheckbox_Click" 
                                              >
                                </CheckBox>

                                </StackPanel>
                            </DataTemplate>
                        </DataGridTemplateColumn.HeaderTemplate>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <CheckBox Name="standardCheckbox" Margin="10,10,0,0" IsChecked= "{Binding  Column1}" Checked="CheckBox_Click_1" Unchecked="UnCheckBox_Click_1"  />
                                    <TextBlock Text="{Binding  Column2}" Padding="10,5,0,0" HorizontalAlignment="Left" />
                                </StackPanel>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>

                    </DataGridTemplateColumn>

                    <DataGridTextColumn  Header="Location"  Binding="{Binding Column3}"/>

                </DataGrid.Columns>
</Datagrid>

I want all the checkbox in standardcheckbox to check when the Upcheckbox are checked during runtime. This is my code behind. Everything is run in a datagrid

myDataItems = new List<DataItem>();
myDataItems.Add(new DataItem { Column1 = true, Column2 = "Gambler", Column3 = "Jurassic Park", Column4 = "CasinoRoyal", Column5 = "JohnGramer" });
            myDataItems.Add(new DataItem { Column1 = true, Column2 = "Gambler",  Column3 = "Lord of the Ring", Column4 = "CasinoRoyal", Column5 = "JohnGramer" });
enter code here
            myDataItems.Add(new DataItem { Column1 = false, Column2 = "Gambler",  Column3 = "Harry potter", Column4 = "CasinoRoyal", Column5 = "JohnGramer" });
missiongrid.ItemsSource = myDataItems;

I try to add in this onCheck method, which is call when the checkbox is checked.

private void UpCheckbox_Click(object sender, RoutedEventArgs e)
    {


        for (int i = 0; i < myDataItems.Count; i++)
        {

            myDataItems[i].Column1 = true;// not working


        }

    }

But it is not working? The checkbox didnt change at all during runtime, only the header checkbox are checked

what should I do?




Laravel validate required_if when current input equals to a value that is inside an array (checkbox with input text)

I got a form with a list of checkboxes. The last one says "other", when clicked, an input text is enabled.

I have this rule where the user can check up to three options.

As you already know, checkboxes are stored in an array.

Should the user check on "other" option, without typing in the input, I want to prompt the user through an error message (validation) that they need to type in the input text, as well.

Here is options_list.blade.php view:

@section('content')
    @if($errors->any())
        <div class="alert alert-danger" role="alert">
            <strong><i class="fas fa-exclamation-triangle"></i>&nbsp;Warning</strong>: The following errors have been found:
            <ul>
                @foreach($errors->all() as $error)
                    <li></li>
                @endforeach
            </ul>
        </div>
    @endif
    <div class="card">
        <div class="card-body">
            <div class="shadow p-3 mb-5 bg-white rounded">
                <p class="h6">
                    Here goes the question text
                </p>
                <p class="text-primary">You can choose up to three options</p>
            </div>
            <div class="shadow">
                <form action="" method="post" id="myForm">
                    <div class="col-lg">
                        @foreach($lineasdeinvestigacion as $lineadeinvestigacion)
                            <div class="custom-control custom-checkbox my-1 mr-sm-2">
                                <input type="checkbox" class="custom-control-input" id="customControlInline" name="lineasdeinvestigacion[]" value="" >
                                <label class="custom-control-label" for="customControlInline"></label>
                            </div>
                        @endforeach
                            <div class="custom-control custom-checkbox my-1 mr-sm-2">
                                <input type="checkbox" class="custom-control-input" id="customControlInlineOtro" name="lineasdeinvestigacion[]" value="other" >
                                <label class="custom-control-label" for="customControlInlineOtro">Other</label>
                                <input placeholder="" type="text" class="form-control form-control-sm" id="fortalecer_otro" name="fortalecer_otro" maxlength="255" value="" disabled>
                            </div>
                            @include('path.to.partials.buttons._continue')
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

And here is the optionsController.php:

public function store(Token $token, Request $request){

        //dd($request->lineasdeinvestigacion);

        //Validating input data
        $this->validate($request,[
            'lineasdeinvestigacion'  =>  'nullable|max:3',
            'fortalecer_otro'        =>  'required_if:lineasdeinvestigacion.*,other|max:255',
        ],[
            'lineasdeinvestigacion.max' => 'You cannot choose more than :max options.',
        ]);
}

This is the array of values chosen from the checkboxes list (dd($request->lineasdeinvestigacion);):

array:4 [▼
  0 => "Procesos socio-culturales"
  1 => "Ciencia, Innovación tecnológica y Educación"
  2 => "Nuevas formas de movilidad"
  3 => "other"
]

However, the validation is not working as it should, as it allows the input text #fortalecer_otro to be empty, when the "other" checkbox option is checked.

How do I fix this? Any ideas?




Unable to get checkboxes values in codeigniter-3

I am using codeigniter 3.16 on an Ubuntu 14.04 server, with apache 2.6 and php 5.6. I have created a multipart form to upload several files and check (or not) a group of checkboxes. My view looks something like:

<form id="creation_form" name="creation_form" class="form-horizontal" action="<?=(isset($edit)?site_url('admin/Projects/edit/').$project->ID:site_url('admin/Projects/create'))?>" method="POST" enctype="multipart/form-data">
// ...
    <?php foreach ($users as $user) { ?>
    <tr>
       <td><input type="checkbox" name="users[]" value="<?= $user->ID ?>" <?=(isset($edit) && isset($project_users[$user->ID])?"checked":"")?>/></td>
       <td><?= $user->name ?></td>
       <td><?= $user->surname ?></td>
       <td><?= $user->email ?></td>
    </tr>
    <?php } ?>
</form>

My controller gets the values of the checked checkboxes with this code:

$users_ids = $this->input->post("users");
if (!isset($users_ids) || sizeof($users_ids) == 0) {
    $error_msg = "Assign at least one user to the project";
}

But it is returning nothing, $users_ids is empty no matters how many checkboxes I check, and I am recovering other inputs like texts and files correctly but not the checkboxes.

Thank you all for your help,

Luis




CheckBox column property

I have created a CheckBox in VB.Net.
I have also created a CheckBox column in one of my database's tables.

I want to assign a Boolean value to it, meaning, if the CheckBox is checked the column value should be 1 in the database, And if it's not checked, the column value should be 0 in the database.

Could you please guide me, so that I'm able to add this property to the CheckBox column.




Store the value of a html checkbox server sided

I am currently working on a project within a company. An application based on simple html/css/js is getting developed atm. So the "website" will only be launched on the intranet of the company. Now my task is it to store checkbox values (checked or unchecked). My problem is, that I can't store the value in the local storage, because it has to be the same everywhere. For example the website will be opened on a computer and a checkbox will be checked. Than the checkbox has to be checked everywhere on any other computer. So I guess I have to store the value of the Checkbox server sided. Do you guys know any simple methode to store the checkbox values? Really hope you guys can help me :D

Thanks a lot!!!

All the best

poza




selecting items in custom listView repeat

It's necessary for me. I have custom listview

    public class MisscallListAdapter extends ArrayAdapter<SmsClass>

This is viewHolder :

        private static class ViewHolder {
               TextView number , name , date , count , time;
               ImageButton btnCall , btnSendsms , btnDelete;
               ImageView imageIcon;
               CheckBox checkBox;
        }

In the getView method I try to get the item that clicked by user and put it in an ArrayList like this :

    final ViewHolder finalViewHolder = viewHolder;
    final View finalConvertView = convertView;
    viewHolder.checkBox.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (finalViewHolder.checkBox.isChecked()) {
                selected.add( smsClass );
                Log.i( "kdsfb", "--->   :  " + selected );
            } else {
                for(int i = 0 ; i < selected.size() ; i++){
                    if(selected.get( i ).getId() == smsClass.getId())
                        selected.remove( i );
                }
            }
        }

    } );

The smsClass above is:

    final SmsClass smsClass = getItem(position);

The problem is when I select the first row of the list(just first item) and make it checked then the fifth item checked too and tenth item and ... help, please.




i want to change the image when i click on a check box

My question is, i have one checkbox and i want, when i click first time on this check box it should change the image from my Image View and when i click again on same checkbox it should change the image in Image View with another one Image.

I Tried:-

checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        myImage.setBackgroundResource(R.drawable.saveimage);
                    }else{
                        myImage.setBackgroundResource(R.drawable.deleteimage);
                    }
                }
            });




Looping on CheckBoxes to sum values corresponding to CheckBoxes

I try to loop on my checkboxes in order to get the sum of data corresponding to those checkboxes, on this base :

exemple

My problem is I have like 200 checkboxes, so I really cant rely on single events. I ve been looking for solutions, and i heard about OLEObject.

Here is my try, please let me know what is wrong and how to write it properly so I can create the adequate loop to my checkboxes (describing the rows corresponding) :

 Sub Sommer()

Dim i As Byte
For i = 7 To 15 
If ThisWorkbook.Worksheets(2).OLEObject("CheckBox" & i).Value = True And ThisWorkbook.Worksheets(2).Cells(i, 4) = "" Then

For Each j In Array(7, 8, 9, 10, 13, 14, 15)
ThisWorkbook.Worksheets(2).Cells(6, j).Value = ThisWorkbook.Worksheets(2).Cells(6, j).Value + ThisWorkbook.Worksheets(2).Cells(i, j).Value
ThisWorkbook.Worksheets(2).Cells(i, 4).Value = "Sélectionné"
Next j

ElseIf ThisWorkbook.Worksheets(2).OLEObject("CheckBox" & i).Object.Value = False And ThisWorkbook.Worksheets(2).Cells(i, 4) = "Sélectionné" Then

For Each j In Array(7, 8, 9, 10, 13, 14, 15)
ThisWorkbook.Worksheets(2).Cells(6, j).Value = ThisWorkbook.Worksheets(2).Cells(6, j).Value - ThisWorkbook.Worksheets(2).Cells(i, j).Value
ThisWorkbook.Worksheets(2).Cells(i, 4).Value = ""
Next j

End If
Next i

End Sub




How to make multiple checkbox in objective c?

I wan to make make multiple selection check box. Should anyone suggest some demo or idea?




check checkboxes Angular 5

I'm new to angular so please excuse me if I'm going to say / ask something very stupid. I followed this example to add checkboxes to my form: enter link description here

Everything works good, I can save the ids of my checkboxes into the database. The problem is that when I try to modify the form I can't check the checkboxes that were checked before and saved into my database ( a list of strings, I know it's not ok but for now I'll keep it like this). I receive the list, I transform it into an array to iterate and then I tried to set value to true to the controls but nothing is working. Can someone help me? These is my file: addmodify.component.ts :`

public natura = [
        { id: 1, name: 'si' },
       { id: 2, name: 'af' },
       { id: 3, name: 'erg'},
       { id: 4, name: 'rid'},
       { id: 5, name: 'ridc' },
       { id: 6, name: 'qual'},
       { id: 7, name: 'Ridte'},
       { id: 8, name: 'Alt'}
    ];
 constructor(
        private _fb: FormBuilder,
        private _avRoute: ActivatedRoute,
        private _suggerimentoService: SuggerimentoService,
        private _nuovoPartecipanteService: NuovoPartecipanteService,
        private toasterService: ToasterService,
        private translate: TranslateService,
        private _router: Router) {
            if (this._avRoute.snapshot.params["id"]) {
                this.id = this._avRoute.snapshot.params["id"];
            }
            else
                this.title = "Inserisci";

          const controls = this.natura.map(c => new FormControl(false));

            this.suggerimentoForm = this._fb.group({
                id: 0,
                partecipanti: ['', [Validators.required]],
                stabilimento: [''],
                approvatoreID: 0,
                titolo: ['', [Validators.required]],
                descrizione: ['', [Validators.required]],
                soluzione: ['', [Validators.required]],
                natura: new FormArray(controls, minSelectedCheckboxes(1)),
                vorrei: [''],
                partecipantiLista: ['']
        });

    }
  ngOnInit() {
      if (this.id > 0) {

          this._suggerimentoService.getSuggerimentoById(this.id)
              .subscribe(resp => {    
                  const controls = this.natura.map(c => new FormControl(false));
                  const listNatura = resp.natura.split(',');
                  listNatura.forEach(function (value) {
                      console.log('valore=',value);
                      controls[0].setValue(true);
                  }); 


                  resp.natura = this.natura;





                  this.suggerimentoForm.setValue(resp);


              }
                  , error => this.errorMessage = error);
      }  
    }
`

and this is my html file:

<form class="k-form" [formGroup]="suggerimentoForm" (ngSubmit)="save()" #formDir="ngForm" novalidate>




Select all CheckBoxes not working inside a webgrid Jquery and ASP.net MVC

I need to select all checkboxes in my table and also I need to select each rowas separately. To achive that I used this post .

This is Jquery Code

@section Scripts{
    <script>
        $(document).ready(function () {

            // 1st replace first column header text with checkbox

            $("#checkableGrid th").each(function () {               
                if ($.trim($(this).text().toString().toLowerCase()) === "{checkall}") {
                    $(this).text('');
                    $("<input/>", { type: "checkbox", id: "cbSelectAll", value: "" }).appendTo($(this));
                    $(this).append("<span>Select All</span>");
                }
            });

            //2nd click event for header checkbox for select /deselect all
            $("#cbSelectAll").live("click", function () {
                var ischecked = this.checked;
                $('#checkableGrid').find("input:checkbox").each(function () {
                    this.checked = ischecked;
                });
            });


            //3rd click event for checkbox of each row
            $("input[name='ids']").click(function () {
                var totalRows = $("#checkableGrid td :checkbox").length;
                var checked = $("#checkableGrid td :checkbox:checked").length;

                if (checked == totalRows) {
                    $("#checkableGrid").find("input:checkbox").each(function () {
                        this.checked = true;
                    });
                }
                else {
                    $("#cbSelectAll").removeAttr("checked");
                }
            });

        });
    </script>
}

And I call it like this,

<div>
    @grid.GetHtml(
    tableStyle: "gridtable",
    htmlAttributes: new { id = "checkableGrid" },
    columns: grid.Columns
        (
    //Here I am going to add checkbox column
            grid.Column(
                format: @<text> <input type="checkbox" value="@item.CustomerID" name="ids" /> </text>,
                header: "{checkall}"
            ),
            grid.Column("CustomerID", "Customer ID"),
            grid.Column("CustomerName", "Customer Name"),
            grid.Column("Address", "Address"),
            grid.Column("City", "City"),
            grid.Column("PostalCode", "Postal Code")
        )
    )
</div>

Each row can select separately, but I can't select all the rows at one time. The Select All check box not showing,instead of that its showing as {checkall}

enter image description here

Please someone help me to solve this.Thank you.




mercredi 26 septembre 2018

Activating two labels with one click

I'm trying to use the "checkbox hack" for a tab group design. clicking on one tab (label) checks a radio box. Then using a ~ selector i can switch the pages between display: block/none;

To illustrate this setup, there's first a row of tab buttons and then a row of pages. The radio boxes live as siblings in the pages container.

+-------------------+
| +------+ +------+ |
| | tab1 | | tab2 | |
| +------+ +------+ |
+-------------------+
| +---------------+ |
| |     page 1    | |
| +---------------+ |
| +---------------+ |
| |     page 2    | |
| +---------------+ |
+-------------------+

This primary feature is working, the pages swap out as expected.

Now for the next part, where im having trouble...

When u click a tab i need to change it's css to look "selected". Since the radio boxes are in the pages container I cant use them and a sibling selector to style the tabs themself. It seems that I need another set of radio buttons, this time within the tabs container.

I've gotten this second "checkbox hack" to work, but now I can't seem to execute the two features at the same time. The tab's are built like:

<label for='tab_selector_1'>
    <input id='tab_selector_1' type='radio'/>
    <label for='page_selector_1' id='tab_1'>TAB NAME</label>
</label>

I'd expected the click to bubble through the two labels and activate both checkboxes, but it only acts on the deepest label. In this case only switching the page and not the tab style.

Is there some way to restructure this, or use different css selectors to make it work? The html can be all changed around if this is a bad way to be going about it, I just need it to be a non-js solution.




C# SQL Check box to be ticked when data present

I am slowing learning my way round c# and SQL. I have started a project that will have a list of checkboxes. I want these checkboxes to be ticked if there is any data present within the table. I am not interested in what data, only if there is data in the table.

I have created a win form project that can connect to the database and show the data in a grid view.

Any help would be fantastic!




Checkbox in Jquery Datable is not Displaying in Angular 5 app

In my angular 5 app am using jquery datable.Am using below code in my component.ts file to display datable with checkbox

 setTimeout(function(){
  $(function(){
    $('#datatable').DataTable({
      pageLength: 10,
      fixedHeader: true,
      responsive: true,
      "sDom": 'rtip',

      columnDefs: [{
          targets: 0,
          'checkboxes': true
      }],
      select:{
        'style': 'multi'
      },
      order:[[1,'asc']]
  });
  });

},0);

Below is my html code:

   <div class="table-responsive row">
     <table class="table table-bordered table-hover" id="datatable">
      <thead class="thead-default thead-lg">
       <tr>
       <th></th>
       <th>Company Name</th>
       <th>Company Code</th>
       </tr>
     </thead>
    <tbody>
     <tr *ngFor="let company of companies">
     <td></td>
     <td></td>
    <td> </td>
    </tr>
   </tbody>
   </table>
   </div>

Kindly please help me on this issue.




Custom checkbox, change on :hover and :checked. Doesn't work

I have problem with my custom checkbox. I would like to change color to green on :hover and yellow on checked.

I tried almost 10 different ways :/ Someone could help me? Code Pen

    <div class="form__checkbox">
      <label for="accept" class="form__checkbox-label">I have read and accept the terms of use.</label>
      <input type="checkbox" id="accept" class="form__checkbox-input">
    </div>

 &__checkbox {
z-index: 2;
position: relative;
&-label {
  cursor: pointer;
  @include inputFonts();
  margin-left: 46px;
  padding: 0.5rem;
  font-size: 1.6rem;

  &::before {
    content: "";
    display: block;
    position: absolute;
    left: 2%;
    top: 50%;
    transform: translateY(-50%);
    height: 20px;
    width: 20px;
    background-color: blue;
    margin-right: 20px;
  }
  &:hover + &::before {
    background-color: red;
    height: 40px;
  }
}
&-input {
  position: absolute;
  top: -999999px;
  opacity: 0;
}

}




Vuejs pass vee-validate to custom checkbox input

I can not make custom checkbox component with vee-validate support. I'm newbie in Vue. In my app checkbox must be required. But it doesn't work. I read a lot of articles about vee-validate and custom inputs, but all examples based on simple custom text inputs.

Below my code at this moment.

Parent component:

    <!-- Custom text input. Vee-validate works nice. -->
    <input-text
        name="email"
        placeholder="Please, enter email"
        label="Email"
        :required="true"
        :type="'email'"
        :value.sync="shareholder.fields.email"
        v-validate.initial="'required|email'"
        data-vv-delay="500"
        :className="{'error': isShowError('email')}"
        :disabled="isDisabled"
    />

    <!-- Custom checkbox input. Vee-validate doesn't work. -->
    <checkbox2
        name="consent"
        v-if="consent"
        class="consent"
        :required="true"
        :disabled="isDisabled"
        :className="{'error': errors.first('consent')}"
        :error="errors.first('consent')"
        v-model="consentStatus"
        v-validate.initial="'required'"
    >
        <br><a :href="consent.link" target="_blank"></a>
    </checkbox2>
    

File check-box.vue:

<template>
    <div class="checkbox"
         :class="{ active: !!value }"
    >
        <label class="control">
            <input
                @change="handleChange"
                type="checkbox"
                :name="name"
                :checked="value"
            />
            <span class="icon-checkbox"></span>
        </label>

        <div class="label">
            <slot />
        </div>
    </div>
</template>

<script src="./check-box.js"></script>
<style lang="stylus" src="./check-box.styl" scoped></style>

File check-box.js:

export default {
    name: 'checkbox2',
    inject: [ '$validator', ],
    // In one of articles I read I must bind event and value
    // with check box like below. But it seems it doesn't work too.
    model: {
        event: 'input',
        value: 'checked',
    },
    props: {
        value: {
            type: Boolean,
            default: false,
        },
        error: {
            type: String,
        },
        name: String,
        disabled: Boolean,
        className: Object,
        required: Boolean,
    },
    data: function() {
        return {
            checked: false,
        }
    },
    methods: {
        handleChange() {
            if (!this.disabled) {
                this.checked = !this.value
                 // If I emit 'change' instead of 'input',
                 // checkbox component works wrong.
                this.$emit('input', this.checked)
            }
        },
    },
    created() {
        this.checked = this.value
        this.$validator = this.$parent.$validator
    },
}




mardi 25 septembre 2018

VBA Filter Based on Checked Boxes

I was wondering if anyone could help me out. I have created a user form that changes the filters on an excel sheet. I have column that contains a priority level from 1-3. When the form is launched i have a option to print the report to PDF, but i want to allow the user to apply/filter out result based on the priority, before they print to PDF. I have three check boxes that i want to use in a filter code (See image below). This where i get stuck, i am not sure how to input code into the Criteria portion so when the user would check the box priority 1, it would filter out that section before it prints. I was going to assign the numerical value that is associated with priority if the value is true. Then use that number as the value "criteria" when the filter is applied. Is there a better way to do this?

ActiveSheet.Range("$W$7:$AG$4501").AutoFilter Field:=6, Criteria:= "What Do i Put Here?" 

enter image description here

enter image description here




javascript extract substring from checkbox innput string value

below a set of checkbox, I would like to retrieve the monetary value of the string from the box to consistent.

for example if the checkbox input value is "Vantaux inegaux maxi vantail 2150 mm $1021.2" i would get the 1021.2 .

here is my code but it returns an error when using .val()

Uncaught TypeError: this.checked.val is not a function

checkbox values

$(document).ready(function() {
  $('input[type=checkbox]').change(function() {
    if(this.checked) {
      console.log (this.checked.val());
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="Vantaux inegaux maxi vantail 2150 mm $1021.2"/>

any suggestion please ?




Checbox Subtraction (android studio, java)

I have an editText which is a decimal input number provided by user. I have a list of checkboxes with different decimal values. How can I subtract (when checked) a certain decimal value (provided by the checkbox) to the editText and then print on a different textView field. Any example would be of great help. Thanks in advance.




add integer values selected by checkbox

TestListModel.class

    public class TestListModel {

    private String testlist_id;
    private String test_price;
    private String test_name;

    private boolean isSelected;

    public TestListModel(String testlist_id, String test_price, String test_name,boolean isSelected) {
        this.testlist_id = testlist_id;
        this.test_price = test_price;
        this.test_name = test_name;
        this.isSelected = isSelected;
    }

    public String getTestlist_id() {
        return testlist_id;
    }

    public void setTestlist_id(String testlist_id) {
        this.testlist_id = testlist_id;
    }

    public String getTest_price() {
        return test_price;
    }

    public void setTest_price(String test_price) {
        this.test_price = test_price;
    }

    public String getTest_name() {
        return test_name;
    }

    public void setTest_name(String test_name) {
        this.test_name = test_name;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }
    }

JsonResponse.java

    public class JSONResponse {

    private TestListModel[] result;

    public TestListModel[] getResult() {
        return result;
    }

    public void setResult(TestListModel[] result) {
        this.result = result;
    }
    }

HealthActivity.java

    public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {

     /*
    *Api call
    * */
    private RecyclerView recyclerView;
    private ArrayList<TestListModel> data;
    private RecyclerAdapter madapter;

    private Button submitButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health_services);
        ButterKnife.bind(this);

        sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());


        submitButton=(Button) findViewById(R.id.submit_button);


     showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));


      initViews();


      submitButton.setOnClickListener(this);


    /*
    * On Click Listner
    * */
    @Override
    public void onClick(View v) {

        switch (v.getId()) {

                    case R.id.submit_button:

                        int totalAmount = 0;
                        int totalPrice = 0;
                        String testName = "";
                        String testPrice="";

                        int count = 0;


                        List<TestListModel> stList = ((RecyclerAdapter) madapter)
                                .getTestList();


                       for (int i = 0; i < stList.size(); i++) {
                            TestListModel singleStudent = stList.get(i);

                           //AmountCartModel serialNumber = stList.get(i);


                           if (singleStudent.isSelected() == true) {

                                testName = testName + "\n" + singleStudent.getTest_name().toString();
                                testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();


                                count++;

                                totalAmount = Integer.parseInt(stList.get(i).getTest_price());

                                totalPrice = totalPrice + totalAmount;

                            }
                       }


                        Toast.makeText(HealthServicesActivity.this,
                                "Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
                                .show();


                        Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);

                        in.putExtra("test_name", testName);
                        in.putExtra("test_price", testPrice);
                        //in.putExtra("total_price",totalPrice);
                        in.putExtra("total_price", totalPrice);
                        in.putExtra("serialNumber", count);
                        startActivity(in);

                        finish();

                        break;



                    /** back Button Click
                    * */
                    case R.id.back_to_add_patient:
                    startActivity(new Intent(getApplicationContext(), PatientActivity.class));
                    finish();
                    break;


            default:
                break;

        }
    }

    /** show center Id in action bar
     * */
    @Override
    protected void onResume() {
        super.onResume();

    showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
    }
    private void showcenterid(LoginModel userLoginData) {
        centerId.setText(userLoginData.getResult().getGenCenterId());
        centerId.setText(userLoginData.getResult().getGenCenterId().toUpperCase());
        deviceModeName.setText(userLoginData.getResult().getDeviceModeName());
    }


    private void initViews() {
        recyclerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        loadJSON();
    }


    private void loadJSON() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(" http://192.168.1.80/aoplnew/api/")
     //                
     .baseUrl("https://earthquake.usgs.gov/fdsnws/event/1/query?")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiInterface request = retrofit.create(ApiInterface.class);
        Call<JSONResponse> call = request.getTestLists();
        call.enqueue(new Callback<JSONResponse>() {


            @Override
            public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {

                JSONResponse jsonResponse = response.body();
                data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
                madapter = new RecyclerAdapter(data);
                recyclerView.setAdapter(madapter);

            }

            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());
            }
        });
    }

HealthRecyclerAdapter.java

    public class RecyclerAdapter extends 
    RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private ArrayList<TestListModel> android;

    public RecyclerAdapter(ArrayList<TestListModel> android) {
        this.android = android;
    }

    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.test_list_row,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, final int position) {

        holder.test_name.setText(android.get(position).getTest_name());
        holder.test_price.setText(android.get(position).getTest_price());




        holder.chkSelected.setChecked(android.get(position).isSelected());

        holder.chkSelected.setTag(android.get(position));

        holder.chkSelected.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                CheckBox cb = (CheckBox) v;
                TestListModel contact = (TestListModel) cb.getTag();

                contact.setSelected(cb.isChecked());
                android.get(position).setSelected(cb.isChecked());

                Toast.makeText(
                        v.getContext(),
                        "Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(), Toast.LENGTH_LONG).show();
            }
        });
    }



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



    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView test_name;
        private TextView test_price;
        public CheckBox chkSelected;

        public TestListModel testLists;

        public ViewHolder(View itemView) {
            super(itemView);

            test_name = (TextView)itemView.findViewById(R.id.test_name);
            test_price = (TextView)itemView.findViewById(R.id.price_name);
            chkSelected = (CheckBox) itemView.findViewById(R.id.check_box);

        }
    }

    // method to access in activity after updating selection
    public List<TestListModel> getTestList() {
        return android;
    }

AmountCartModel.java

    public class AmountCartModel {


    private String testName;
    private String testPrice;
    private Integer serialNumber;
    private Integer totalPrice;


    public AmountCartModel() {
        this.testName = testName;
        this.testPrice = testPrice;
        this.serialNumber = serialNumber;
        this.totalPrice = totalPrice;
    }


    public String getTestName() {
        return testName;
    }

    public void setTestName(String testName) {
        this.testName = testName;
    }

    public String getTestPrice() {
        return testPrice;
    }

    public void setTestPrice(String testPrice) {
        this.testPrice = testPrice;
    }

    public Integer getSerialNumber() {
        return serialNumber;
    }

    public void setSerialNumber(Integer serialNumber) {
        this.serialNumber = serialNumber;
    }

    public Integer getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(Integer totalPrice) {
        this.totalPrice = totalPrice;
    }
    }

AmountCartActivity.java

    public class AmountCartActivity extends AppCompatActivity implements View.OnClickListener {

    @BindView(R.id.total_price)
    TextView totalPriceDisplay;

    SharePreferenceManager<LoginModel> sharePreferenceManager;

    private RecyclerView recyclerView;

    List<AmountCartModel> mydataList ;

    private MyAdapter madapter;

    Bundle extras ;
    String testName="";
    String testPrice="";
    String totalPrice= "";

    int counting = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_amount_cart);
        ButterKnife.bind(this);


        sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());


     showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));


        mydataList = new ArrayList<>();
        /*
        * Getting Values From BUNDLE
        * */
        extras = getIntent().getExtras();

        if (extras != null) {

            testName = extras.getString("test_name");
            testPrice = extras.getString("test_price");
            totalPrice = String.valueOf(extras.getInt("total_price"));

            counting = extras.getInt("serialNumber");

            //Just add your data in list
            AmountCartModel mydata = new AmountCartModel();  // object of Model Class
            mydata.setTestName(testName );
            mydata.setTestPrice(testPrice);

            mydata.setTotalPrice(Integer.valueOf(totalPrice));

            mydata.setSerialNumber(counting);

            mydataList.add(mydata);

            //totalPriceDisplay.setText(totalPrice);

        }


        madapter=new MyAdapter(mydataList);
        madapter.setMyDataList(mydataList);
        recyclerView = (RecyclerView)findViewById(R.id.recyler_amount_cart);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(madapter);

RecyclerAdapter.java //RecyclerAdapter for AmountCart

     public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> 
    {

        private List<AmountCartModel> context;
        private List<AmountCartModel> myDataList;

        public MyAdapter(List<AmountCartModel> context) {
            this.context = context;
            myDataList = new ArrayList<>();
        }



       @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) 
    {

            // Replace with your layout
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amount_cart_row, parent, false);
            return new ViewHolder(view);
        }


        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            // Set Your Data here to yout Layout Components..

            // to get Amount
           /* myDataList.get(position).getTestName();
            myDataList.get(position).getTestPrice();*/


            holder.testName.setText(myDataList.get(position).getTestName());

       holder.testPrice.setText(myDataList.get(position).getTestPrice());

       holder.textView2.setText(myDataList.get(position).getSerialNumber());

        }


        @Override
        public int getItemCount() {
            /*if (myDataList.size() != 0) {
                // return Size of List if not empty!
                return myDataList.size();
            }
            return 0;*/
            return myDataList.size();
        }


        public void setMyDataList(List<AmountCartModel> myDataList) {
            // getting list from Fragment.
            this.myDataList = myDataList;
            notifyDataSetChanged();
        }


        public class ViewHolder extends RecyclerView.ViewHolder {

            TextView testName,testPrice,textView2;


            public ViewHolder(View itemView) {
                super(itemView);
                // itemView.findViewById

                testName=itemView.findViewById(R.id.test_name_one);
                testPrice=itemView.findViewById(R.id.test_price);
                textView2=itemView.findViewById(R.id.textView2);
            }
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();

        startActivity(new 
     Intent(AmountCartActivity.this,HealthServicesActivity.class));
        finish();

    }

}

This is my code.

  1. Here I am taking HealthActivity and in this class by using recycler view I have displayed testList in recycler view. I am passing testList whichever I am selecting through checkbox to AmountCartActivity of recycler View, And, I am calculating total amount of the selected testList and I am getting the result and that result I am passing to the AmountCart Activity through bundle and I am getting correct result in bundle, but, when I am trying to display total amount in a textView its showing me nothing.

And, my second problem is,

  1. I am trying to display serial number to to my AmountCartActivity of recycler view whichever I am selecting from previous HealthCartActivity using checkbox. And, I have implemented some code but I am not getting how to solve it. please help me.



lundi 24 septembre 2018

Python Django delete multiple records using a check box and a delete button

Looking for some guidance on how to delete multiple rows (a table is produced using a listview - postgreSQL) using a check box and a delete button.




Can you make a "Switch" statement with expression of method "getElementByName" with check boxes with the same name? (JavaScript)

This is my function:

function finalOutput() {
var text, text2, q = document.getElementByName("checker").value;

switch(q){
    case 1:
        text = "my role is role1";
    break;
    case 2:
        text = "my role is role2";
    break;
    case 3:
        text = "my role is role3";
    break;
    case 4:
        text2 = "my parameter is parameter1";
    break;
    case 5:
        text2 = "my parameter is parameter2";
    break;
    case 6:
        text2 = "my parameter is parameter3";
    break;
    default:
    text = "Please check if you fill all details...";
    }
document.getElementById("output").innerHTML = text;
document.getElementById("output2").innerHTML = text2;
}

This is the checkboxes in html:

role1:  <input type="checkbox" id="1" onclick="selectOnlyThis(this.id)" 
value="1" name="checker"/> </br>
role2:  <input type="checkbox" id="2" onclick="selectOnlyThis(this.id)"         
value="2" name="checker"/> </br>
role3:  <input type="checkbox" id="3" onclick="selectOnlyThis(this.id)"     
value="3" name="checker"/> </br>
parameter1:  <input type="checkbox" id="4" 
onclick="selectOnlyThis2(this.id)" value="4" name="checker" /> </br>
parameter2:  <input type="checkbox" id="5" 
onclick="selectOnlyThis2(this.id)" value="5" name="checker" /> </br>
parameter3:  <input type="checkbox" id="6" 
onclick="selectOnlyThis2(this.id)" value="6" name="checker" />

I want that the switch will get the value of each checkbox and will do what im told him accordingly. I think that the problem is with the cases of switch but not sure. I tried to do it with "if" but couldn't make it work.




Check_box_tag input id

I have a check_box_tag that looks like this :

check_box_tag('shipping_method[shipping_categories][]', category.id, @shipping_method.shipping_categories.include?(category))

When inspecting the output in browser, I have the following :

<input id="shipping_method_shipping_categories_" name="shipping_method[shipping_categories][]" type="checkbox" value="1" />

I don't get why the id has no "id", meaning that the underscore at the end of id="shipping_method_shipping_categories_" makes me expect an id for this particular shipping_category.

Any of you guys and gals have thoughts on this ?

Thanks !




how to add integer values in Recycler View

How to add integer values selected by checkbox by using bundle. I am using for loop to add the value and through bundle i am passing the values to activities. I am accessing the list from adapter class. Adapter class is having RecyclerView. And, in AmountCart Activity i am setting the value of the selected checklist value.

MainActivity.class

 int totalAmount = 0;
 int totalPrice = 0;
 String testName = "";
 String testPrice="";


  List<TestListModel> stList = ((RecyclerAdapter) madapter)
                            .getTestList();

                   for (int i = 0; i < stList.size(); i++) {
                        TestListModel singleStudent = stList.get(i);

                        if (singleStudent.isSelected() == true) {

                            testName = testName + "\n" + singleStudent.getTest_name().toString();
                            testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();

                            totalAmount = Integer.parseInt(stList.get(i).getTest_price().toString());

                            totalPrice = totalPrice + totalAmount;

                        }
                   }


                    Toast.makeText(HealthServicesActivity.this,
                            "Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
                            .show();


                    Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);

                    in.putExtra("test_name", testName);
                    in.putExtra("test_price", testPrice);
                    in.putExtra("total_price",totalPrice);
                    startActivity(in);

                    finish();

                    break;

AmountCart.class

    mydataList = new ArrayList<>();
    /*
    * Getting Values From BUNDLE
    * */
    extras = getIntent().getExtras();

    if (extras != null) {

        testName = extras.getString("test_name");
        testPrice = extras.getString("test_price");
        totalPrice=extras.getString("total_price");


        //Just add your data in list
        AmountCartModel mydata = new AmountCartModel();  // object of Model Class
        mydata.setTestName(testName );
        mydata.setTestPrice(testPrice);
        mydataList.add(mydata);


        totalPriceDisplay.setText(totalPrice);

    }

TestModel.class

public class TestListModel {

private String testlist_id;
private String test_price;
private String test_name;

private boolean isSelected;

public TestListModel(String testlist_id, String test_price, String test_name,boolean isSelected) {
    this.testlist_id = testlist_id;
    this.test_price = test_price;
    this.test_name = test_name;
    this.isSelected = isSelected;
}

public String getTestlist_id() {
    return testlist_id;
}

public void setTestlist_id(String testlist_id) {
    this.testlist_id = testlist_id;
}

public String getTest_price() {
    return test_price;
}

public void setTest_price(String test_price) {
    this.test_price = test_price;
}

public String getTest_name() {
    return test_name;
}

public void setTest_name(String test_name) {
    this.test_name = test_name;
}

public boolean isSelected() {
    return isSelected;
}

public void setSelected(boolean isSelected) {
    this.isSelected = isSelected;
}
}




call a function when check box is checked by [(ngModel)]="name1"

I have bound all checkboxes of a column with two-way binding. If I click on a checkbox then all the checkboxes of corresponding column get checked. But it is not calling the function that is defined with every checkbox checked condition. How can I call those functions? I am using angular 6.




Filter data from index view using checkbox

Hello Im working on a rails project. Its a project that selects a list of contacts from the phonebook(index view) and sends texts to only the selected. So I would like to introduce a checkbox on the index view that selects a few of the contacts and sends this data to my controller. Any help on how I can go about this?




dimanche 23 septembre 2018

Javascript JQuery toggle nested elements with checkbox

I am currently having troubles getting into my list subclass. The idea is to create multi-level unfolding list with check boxes working as buttons. Right now it all folds/unfolds at the same time and we want elements to unfold by checking/unchecking it's parent.

I do realize I can use less/sass to hide/show those elements by clicking on them, but I would like to learn how do do it with jQuery.

$(document).ready(() => {

 $('.sub-ul').hide();
  
 $('.side-checkbox').each(function () {
    var obj = $('.sub-ul');
    $(this).click(function () {
      if ($(this).is(':checked')) {
        obj.show(300);
      } else {
        obj.hide(200);
      }
    });
  });
});
a {
  text-decoration: none;
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="ul-nav">
  <li class="li-nav">
  
    <a class="side-menu-checkbox" href="#">(A)Lorem</a>

    <input type="checkbox" name="a" id="a" class="side-checkbox">

    <ul class="ul-nav sub-ul">
      <li class="li-nav">
        <a href="#">(B)Ipsum</a>

        <input type="checkbox" name="a" id="b" class="side-checkbox">

        <ul class="ul-list sub-ul">
          <li class="li-nav"><a href="#">(C)Dolorem</a></li>
          <li class="li-nav"><a href="#">(C)Dolorem</a></li>
          <li class="li-nav"><a href="#">(C)Dolorem</a></li>
        </ul>
      </li>
      <li>
        <a href="#" class="side-menu-plus">(B)Ipsum</a>

        <input type="checkbox" name="a" id="c" class="side-checkbox">

        <ul class="ul-list sub-ul">
          <li class="li-nav"><a href="#">(C)Dolorem</a></li>
          <li class="li-nav"><a href="#">(C)Dolorem</a></li>
          <li class="li-nav"><a href="#">(C)Dolorem</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li class="li-nav"><a href="#">(A)Lorem</a></li>
  <li class="li-nav">
    <a class="side-menu-checkbox" href="#">(A)Lorem</a>

    <input type="checkbox" name="a" id="a" class="side-checkbox">

    <ul class="ul-nav sub-ul">
      <li class="li-nav">
        <a href="#">(B)Ipsum</a>

        <input type="checkbox" name="a" id="b" class="side-checkbox">
        
        <ul class="ul-list sub-ul">
          <li class="li-nav"><a href="#">(C)Dolorem</a></li>
          <li class="li-nav"><a href="#">(C)Dolorem</a></li>
          <li class="li-nav"><a href="#">(C)Dolorem</a></li>
        </ul>
      </li>
      <li>
        <a href="#" class="side-menu-plus">(B)Ipsum</a>

        <input type="checkbox" name="a" id="c" class="side-checkbox">
        

        <ul class="ul-list sub-ul">
          <li class="li-nav"><a href="#">(C)Dolorem</a></li>
          <li class="li-nav"><a href="#">(C)Dolorem</a></li>
          <li class="li-nav"><a href="#">(C)Dolorem</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li class="li-nav"><a href="#">(A)Lorem</a></li>
</ul>

element.




Checkbox and ComboBox javaFX

i'd like to find out, which CheckBoxes are checked and which are unchecked by one method. Furthermore, i'd like to find out how can i add label in ChomboBox, E.G. there are numbers to choose, and from 1-9 there is heading "weak",from 10-20 there is heading "strong", but you can choose only from numbers and not from headings.

Thanks for any suggestion

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.text.Font;

import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {
    public Label l1,l2,l3,l4,l5,l6,l7,l8;
    public Button generovatB;
    public TextField jtxt1;
    public ComboBox cbox1;
    public CheckBox cb1,cb2,cb3,cb4,cb7;
    public Font x2;
    public ImageView imgvBck;
    //created by Z.K. =
    private char[] lower = {'a','b','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    private char[] upper = {'A','B','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    private char[] special = {'#','&','@','{','}','[',']','+','-','*','/','?','.',':','!','§',')','(','/','%','=',';','<','>','ß','$'};
    private char[] numbers = {'1','2','3','4','5','6','7','8','9','0'};
    private String[] words = new String[1000];



    public void generovatB(ActionEvent actionEvent) {


    }


    public void naplnPole(){


}

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        Image pozadi = new Image("obr.png",650,500,true,false,false);
        imgvBck.setImage(pozadi);
        ObservableList<String> options =
                FXCollections.observableArrayList("5","7","9","15","18"
                );
        cbox1.setItems(options);

    }
}




Add a checkboxes to existing Treeview in WPF

I have an existing treeview in WPF in which I would like to add checkboxes

Here the code

I have a class Person which contains all the structure

Person.cs

public class Person
    {
        readonly List<Person> _children = new List<Person>();
        public IList<Person> Children
        {
            get { return _children; }
        }

        public string Name { get; set; }
    }

As I read in some other posts, I use ViewModel

PersonViewModel.cs

public class PersonViewModel : INotifyPropertyChanged
    {
        #region Data
        readonly ReadOnlyCollection<PersonViewModel> _children;
        readonly PersonViewModel _parent;
        readonly Person _person;

        bool _isExpanded=true;
        bool _isSelected;
        #endregion Data

        #region Constructors
        public PersonViewModel(Person person): this(person, null)
        {
        }

        private PersonViewModel(Person person, PersonViewModel parent)
        {
            _person = person;
            _parent = parent;

            _children = new ReadOnlyCollection<PersonViewModel>(
                    (from child in _person.Children
                     select new PersonViewModel(child, this))
                     .ToList<PersonViewModel>());
        }
        #endregion Constructors

        #region Person Properties
        public ReadOnlyCollection<PersonViewModel> Children
        {
            get { return _children; }
        }

        public string Name
        {
            get { return _person.Name; }
        }

        #endregion Person Properties

        #region Presentation Members
        #region IsExpanded

        /// <summary>
        /// Gets/sets whether the TreeViewItem 
        /// associated with this object is expanded.
        /// </summary>
        public bool IsExpanded
        {
            get { return _isExpanded; }
            set
            {
                if (value != _isExpanded)
                {
                    _isExpanded = value;
                    OnPropertyChanged("IsExpanded");
                }

                // Expand all the way up to the root.
                if (_isExpanded && _parent != null)
                    _parent.IsExpanded = true;
            }
        }

        #endregion IsExpanded

        #region IsSelected

        /// <summary>
        /// Gets/sets whether the TreeViewItem 
        /// associated with this object is selected.
        /// </summary>
        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                if (value != _isSelected)
                {
                    _isSelected = value;
                    OnPropertyChanged("IsSelected");
                }
            }
        }

        #endregion IsSelected

        #region NameContainsText

        public bool NameContainsText(string text)
        {
            if (String.IsNullOrEmpty(text) || String.IsNullOrEmpty(this.Name))
                return false;

            return Name.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) > -1;
        }

        #endregion NameContainsText

        #region Parent

        public PersonViewModel Parent
        {
            get { return _parent; }
        }

        #endregion Parent

        #endregion Presentation Members        

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion INotifyPropertyChanged Members
    }

The family tree ViewModel

FamilyTreeViewModel.cs

public class FamilyTreeViewModel {

#region Data
readonly PersonViewModel _rootPerson;
#endregion Data

#region Constructor
public FamilyTreeViewModel(Person rootPerson)
{
    _rootPerson = new PersonViewModel(rootPerson);

    FirstGeneration = new ReadOnlyCollection<PersonViewModel>(
        new PersonViewModel[]
        {
            _rootPerson
        });
}
#endregion Constructor

#region Properties
#region FirstGeneration
/// <summary>
/// Returns a read-only collection containing the first person 
/// in the family tree, to which the TreeView can bind.
/// </summary>
public ReadOnlyCollection<PersonViewModel> FirstGeneration { get; }
#endregion FirstGeneration
#endregion Properties

}

The xaml code MainWindow.xaml

<TreeView ItemsSource="{Binding FirstGeneration}">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
            <Setter Property="FontWeight" Value="Normal" />
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="FontWeight" Value="Bold" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </TreeView.ItemContainerStyle>

    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Name}" />

        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

MainWindow.xaml.cs

  public partial class MainWindow : Window
    {
        readonly FamilyTreeViewModel _familyTree;

        public MainWindow()
        {
            InitializeComponent();
            Person rootPerson = new Person
            {
                Name="Application Architect Right",
                Children =
                {
                    new Person
                    {
                        Name="Generate"
                    },
                    new Person
                    {
                        Name="Instances rights",
                        Children =
                        {
                            new Person
                            {
                                Name = "Create"
                            },
                            new Person
                            {
                                Name = "Modify"
                            },
                            new Person
                            {
                                Name = "Delete"
                            },
                            new Person
                            {
                                Name = "Exceptions Management"
                            }
                        }

                    },
                    new Person
                    {
                        Name="Templates rights",
                        Children =
                        {
                            new Person
                            {
                                Name = "Create"
                            },
                            new Person
                            {
                                Name = "Modify"
                            },
                            new Person
                            {
                                Name = "Delete"
                            }
                        }
                    },
                    new Person
                    {
                        Name="Parameters rights",
                        Children =
                        {
                            new Person
                            {
                                Name = "Create"
                            },
                            new Person
                            {
                                Name = "Modify"
                            },
                            new Person
                            {
                                Name = "Delete"
                            }
                        }
                    },
                }
            };


            // Create UI-friendly wrappers around the 
            // raw data objects (i.e. the view-model).
            _familyTree = new FamilyTreeViewModel(rootPerson);


            // Let the UI bind to the view-model.
            DataContext = _familyTree;

        }
    }

Can someone can help me?

Thanks in advance




samedi 22 septembre 2018

Pass array from checkboxes and insert multiple rows to database CodeIgniter

Here is my view:

<?php foreach ($list_peserta as $show): ?>
                <label>
                <input type="checkbox" name="undangan[]" value="<?php echo $show->email ?>" />
                <?php echo $show->nama ?></label>
              <?php endforeach; ?>
            </div>
          </div>
          <div class="form-actions">
            <input type="submit" value="Kirim" class="btn btn-info">
          </div>
          <?php echo form_close(); ?>

My Controller:

$data   =   array();
        $count  =   count($this->input->get_post['undangan']);
        for ($i = 0; $i <= $count ; $i++) {
            $data[] =   array(  
                                'id_acara'      =>  $this->input->post['id'][$i],
                                'email_peserta' =>  $this->input->post['undangan'][$i],
                                'status'        =>  ['Diundang'][$i]
                            );

            $this->db->insert_batch('kehadiran', $data);

I'm getting this error: enter image description here

Please help!




Boolean android.widget.checkbox.is checked error

I am working on a quiz that is required to have 4 questions.

Multiple answer questions require checkboxes, single answer questions require a radio button and one text entry. There must also be one if/else statement which I have been having trouble setting up for the checkboxes.

At the end of submission a toast message is to display the total score for all questions answered, for the sake of simplicity I made the quiz to only have the right options as selectable options.

I found a similar question in NullPointerException when using CheckBox in android .

However unlike in that case I have my set content view pointing to my layout activity page.

I am able to get a toast message to appear once I click the submit button however once I tried to run the app on my phone after inputting the check box if statements I receieve the error:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.ricardo.quizapp, PID: 23030
                  java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference
                      at com.example.ricardo.quizapp.MainActivity$1.onClick(MainActivity.java:62)
                      at android.view.View.performClick(View.java:6205)

Here is my activity main xml code

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:textSize="20sp"
        android:layout_height="wrap_content"
        android:text=" Question 1. Name  the main characters in a story about witches and wizards"
        android:id="@+id/question1"
         />

    <CheckBox
       android:id="@+id/checkbox"
        android:text= "Hermione"
        android:layout_marginTop="240dp"
        android:textSize="20sp"
        android:layout_width="wrap_content"


        android:layout_height="wrap_content"  >  </CheckBox>

    <CheckBox
        android:id="@+id/Harry"
        android:text= "Harry"
        android:layout_marginTop="200dp"
        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"  >  </CheckBox>

    <CheckBox
        android:id="@+id/Ron"
        android:onClick="checked"
        android:layout_marginTop="170dp"
        android:textSize="20sp"
        android:text= "Ron"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"  >  </CheckBox>








    <TextView
        android:layout_width="wrap_content"
        android:layout_marginTop="290dp"
        android:textSize="20sp"

        android:layout_height="wrap_content"
        android:text=" Question 2. Who dropped harry off with the dursleys?">


    </TextView>



            <RadioButton
                android:layout_marginTop="400dp"
                android:textSize="20sp"
                android:id="@+id/hagrid"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="hagrid"
                android:textAppearance="?android:textAppearanceMedium"/>
    <RadioButton
        android:id="@+id/snape"
        android:layout_width="wrap_content"
        android:layout_marginTop="370dp"
        android:textSize="20sp"
        android:clickable="false"
        android:layout_height="wrap_content"
        android:text="snape"
        android:textAppearance="?android:textAppearanceMedium"/>



    <TextView
        android:layout_width="wrap_content"
        android:layout_marginTop="430dp"
        android:textSize="20sp"
        android:layout_height="wrap_content"
        android:text=" Question 3. Who was famous for saying the fan favorite line: Turn to page 394?"
        />
    <RadioButton
        android:layout_marginTop="650dp"

        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hagrid"
        android:clickable="false"

        android:textAppearance="?android:textAppearanceMedium" />


    <RadioButton
        android:layout_marginTop="700dp"

        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="false"

        android:text="Dumbledore"
        android:textAppearance="?android:textAppearanceMedium" />






    <RadioButton
        android:layout_marginTop="600dp"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Snape"
        android:textSize="20sp"
        android:textAppearance="?android:textAppearanceMedium" />



<TextView
    android:text=" Question 4. Give the last name of the author of the harry potter series lower case spelling:"
    android:layout_width="wrap_content"
    android:layout_marginTop="760dp"
    android:id="@+id/Edit_Text"

    android:textSize="20sp"
    android:layout_height="wrap_content" />


    <EditText
        android:hint="Enter Answer"
        android:layout_marginTop="900dp"
        android:textSize="20sp"
        android:layout_width="match_parent"
        android:id="@+id/answer"
        android:layout_height="wrap_content" />

    <Button
        android:layout_width="wrap_content"
        android:text="Click me to submit the answer"
        android:layout_marginTop="960dp"

        android:id="@+id/button"

        android:layout_height="wrap_content" />
<TextView
    android:layout_width="wrap_content"
    android:id="@+id/rowling"

    android:layout_height="wrap_content" />
      <Button
          android:layout_width="200dp"
          android:layout_centerHorizontal="true"
          android:layout_height="wrap_content"
          android:text="Click me to submit your answers"
          android:layout_marginTop="1200dp"
          android:id="@+id/finalscore"
          android:onClick="finalscore"


          android:textSize="20sp"/>





</RelativeLayout>
</ScrollView>

Java code below

    enter code here
package com.example.ricardo.quizapp;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {
    TextView Question1;
    Button finalscore;
    CheckBox Hermione;
    CheckBox Harry;
    CheckBox Ron;
    Context context;
    CheckBox sam;
    EditText answer;
    TextView rowling;
    Button submit;
    public Button button;
    String getMystring="the correct answer is hermione, ron, and harry";
    String mystring = "rowling";
    RadioButton hagrid;
    RadioButton snape;
    TextView showfinalscore;
    String string= "you are correct";
    int number =0;
    String stringg= "this is the last score";
    String string2= "this is the wrong choise";


    @Override


    protected void onCreate(Bundle savedInstanceState) {







        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        button =  findViewById(R.id.finalscore);
        button.setOnClickListener(new View.OnClickListener() {



            @Override
            public void onClick(View view) {




                if (Hermione.isChecked()==true && Ron.isChecked()==true && Harry.isChecked()== true) {
                    Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
                } else if (Hermione.isChecked()) {
                    Toast.makeText(getApplicationContext(), string2, Toast.LENGTH_LONG).show();
                }}});}}