mercredi 31 janvier 2018

Trying to set and get Settings.default.XXXXX, passing the XXXX part in code

I have created a setting - Let's say Properties.Settings.Default.LightOn.

I have a form with a bunch of checkboxes and what I want to do is grab the name of the textbox (which matches the name of the setting) and loop through them to update the settings.

Something like where I have passed a checkbox with text = "LightOn"

foreach (CheckBox c in this.form){
string myCtext = c.text;  //This will grab the text

//This is where the problem is...I am not sure how to construct this.  
chk+myCtext+.checked = Settings.Default.+myCtext;

//OR
var myvar = chk+myCtext+".checked = Settings.Default."+myCtext;
myVar;
}

Just not sure how to put it together and I am trying to save myself the steps of having to manually type every assignment out manually.




Changing app theme with checkbox (with java)

I'm adding a Dark Mode to my app and I've created a checkbox in the 3-dot menu (toolbar).

I want to make the app change the theme to Dark when the checkbox is checked, and revert it back to the Main theme when unchecked.

Here is my current code for onClick of Dark Mode Checkbox button:

    if (id == R.id.dark_mode) {

            switch (item.getItemId()) {
                case R.id.dark_mode:
                    if (item.isChecked()) {
// If item already checked then unchecked it
                        item.setChecked(false);
                    } else {
// If item is unchecked then checked it
                        item.setChecked(true);
                    }
                default:
                    return super.onOptionsItemSelected(item);
            }
        }

How can I do this using java?




How to save boolean states from an array of checkboxes and load their states when the adapter is loaded using SharedPreferences

I have a CustomAdapter for a listview and I need to save all checkbox states from an array of boolean using SharedPreferences, I would like to save the name of the trick (an Array of String) as the Key and the state for each trick.

Everytime the user change any state it needs to update inside the SharedPreference for the clicked trick.

I tried the two methods below to test but it didn't work, I don't know how to make this work.

storeArray() and loadArray().

listview with the checkboxes

public class CustomAdapter0 extends BaseAdapter {

    public CustomAdapter0(String[] tricks, Context context) {
        this.tricks = tricks;
        this.context = context;
        isClicked = new boolean[tricks.length];
        for(int i = 0; i < isClicked.length; i++) isClicked[i] = false;

    }

    private String[] tricks;
    private Context context;
    private boolean[] isClicked;
    private LayoutInflater layoutInflater;


    @Override
    public int getCount() {
        return tricks.length;
    }

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

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

    @Override
    public View getView(final int i, View convertView, ViewGroup viewGroup) {

        View row = convertView;

        if(convertView == null){

            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.custom_listview_tricks, null);
        }

        TextView textView = row.findViewById(R.id.name_xml);
        ImageButton imageButton = row.findViewById(R.id.unmastered_xml);

        textView.setText(tricks[i]);
        if (isClicked[i]) imageButton.setBackgroundResource(R.drawable.mastered);
        else imageButton.setBackgroundResource(R.drawable.unmastered);



        **loadArray**(tricks[i], context);


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

                ImageButton clickedView = (ImageButton) view;
                int clickedPosition = (int)clickedView.getTag();
                isClicked[clickedPosition] = !isClicked[clickedPosition];
                notifyDataSetChanged();

                **storeArray**(isClicked, tricks, context);

            }
        });

        imageButton.setTag(i);

        return row;
    }

    public boolean **storeArray**(boolean[] array, String[] arrayName, Context mContext) {

        SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(arrayName +"_size", array.length);

        for(int i=0;i<array.length;i++)
            editor.putBoolean(arrayName + "_" + i, array[i]);

        return editor.commit();
    }


    public Boolean[] **loadArray**(String arrayName, Context mContext) {

        SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
        int size = prefs.getInt(arrayName + "_size", 0);
        Boolean array[] = new Boolean[size];
        for(int i=0;i<size;i++)
            array[i] = prefs.getBoolean(arrayName + "_" + i, false);

        return array;
    }

}




Appcompat checkbox background highlighted instead of the tick

I'm changing from ActionBarSherlock to AppCompat. Previously when a checkbox was checked, the background stayed the same and the tick appeared in the box in the highlight colour. With AppCompat, the background is highlighted, and the tick is outlined in the original background colour.

Is there any way to duplicate the previous behaviour, which in my view looks much better?

(Asking here is a last resort - I have searched extensively for a solution.)

(I am deriving my Preference activity from AppCompatPreferenceActivity, the code for which I found after searching, and implemented it as a class extending PreferenceActivity in my application)




Checkbox.setOnCheckedChangeListener is not working for ExpandableListView

I'm trying to display expandableListView in android alertDialog everything is working fine. I'm able to check/un-check the checkbox that I'm showing in childView But I have to do some stuff when I check/un-check the checkbox, Here its not working.
When I implement checkbox check listener in adapter class it works perfect, I need it in the class from where I'm setting adapter. I searched over the internet and tried many ways, Now when I make the child click listener to false inside adapter like

itemView.setClickable(false);

The click listener in the origin class is working. But on expand/collapse the expandableListView my checkbox get unselected.

Here is what I have When I size to expand its child the child of color get un-selected

enter image description here

Here is my code in origin class called ProductsFragment the relevant code

ExpandableListView myList = new ExpandableListView(context);
                ExpandableListAdapter myAdapter = new ExpandableListAdapter(
                        headerList, hashMap, true);
                myList.setAdapter(myAdapter);
                myList.setGroupIndicator(null);

                builder.setView(myList);
                myList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                    @Override
                    public boolean onChildClick(final ExpandableListView parent, View v,
                                                final int groupPosition, final int childPosition, long id) {
                        MenuSubCategory subCategory = (MenuSubCategory) parent.getExpandableListAdapter()
                                .getChild(groupPosition, childPosition);
                        CheckBox checkBox = (CheckBox) v;
                        checkBox.toggle();
                        utils.printLog("IsChecked = " + ((CheckBox) v).isChecked());
                        if (((CheckBox) v).isChecked()) {
                            utils.printLog("SubCatListItemId = " + subCategory.getMenuSubCategoryId());
                            selectedFilters.add(subCategory.getMenuSubCategoryId());
                        } else {
                            String filterId = subCategory.getMenuSubCategoryId();
                            if (!filterId.isEmpty())
                                selectedFilters.remove(filterId);
                        }
                        return true;
                    }
                });

I did not get the difference between return true/ return false in expandableListViews child click listener. I tried both way.

Please tell me the best way to implement expandableListView with chechbox in it. In a way that will make it work checkbox check/un-check and retain the check state on expand/collapse.

All effort would be appreciated. Thanks in advance.

Additional: for the statement

I'm able to check/un-check the checkbox

that means only selection/un-selection animation happens not the event, and its the case when I do not write itemView.setClickable(false); in adapter class




Inserting checkboxes inside php code

I'm trying to use checkboxes to update information in a MySQL database.

The 'Sent' column is a Boolean.

Is there a way to put a checkbox inside my php code,tbody so, instead of <td>".$infoItems['Sent']."</td> there's a checkbox instead of zeroes.

<table class="scroll">
  <thead>
    <tr>
      <th>Schools Name</th>
      <th>Schools Email</th>
      <th>Sent</th>
    </tr>
  </thead>

  <tbody>
      <?php

      $execItems = $conn->query("SELECT Name,SchoolMail,Sent FROM Schools");

      while($infoItems = $execItems->fetch_array())
      {
        echo    "
                <tr>
                    <td>".$infoItems['Name']."</td>
                    <td>".$infoItems['SchoolMail']."</td>
                    <td>".$infoItems['Sent']."</td>
                </tr>
            ";
        }
    ?>
    </tbody>
</table>
</body>

</html>




Keep Radio and Checkbox value after submit in Razor page

I have the following code:

<div>
    <form method="post">
    <div>
        <input id="BatteryPercentage" min="0" max="100" name="BatteryPercentage" value="@Model.BatteryPercentage" type="number" placeholder="Insert Battery Percentage (0->100)">
        <button type="submit" asp-page-handler="BatteryPercentage">UPDATE!</button><br>
        </div>

                <div>

        <input type="number"  id="ACtemperature" min="15" max="30" name="ACtemperature" value="@Model.ACtemperature" placeholder="Insert AC Temperature (15°->30°)">
        <button type="submit" asp-page-handler="ACtemperature">UPDATE!</button><br>

        </div>
                <div>

        <label>Insert AC Power: </label>
        <input type="number"  id="ACpower" min="0" max="4" name="ACpower" value="@Model.ACpower" placeholder="Insert AC Power (0->4)">
        <button type="submit" asp-page-handler="ACpower">UPDATE!</button><br>
        </div>
                        <div>

            <label>Insert AC Direction: </label>
            <input type="radio" value="Model.ACopt1" name="ACdir"> 1 
            <input type="radio" value="2"  name="ACdir"> 2 
            <input type="radio" value="3"  name="ACdir"> 3 
            <button type="submit" asp-page-handler="ACdirection">UPDATE!</button><br>
            </div>
                    <div>


            <input  type="checkbox" name="ACopt1" value="1"> Opt1 
            <input  type="checkbox" name="ACopt2" value="2" > Opt2 
            <input  type="checkbox" name="ACopt3" value="3" > Opt3 
        <button type="submit" asp-page-handler="ACopt">UPDATE!</button><br>
    </div>

    </form>
 </div>

I want to keep the value of all input in my form after every submit. The "number" and "text" input are ok with the code "value="@Model.x" because in the chtml.cs I have:

        [BindProperty]
    public int BatteryPercentage { get; set; }
    [BindProperty]
    public int BatteryStatus { get; set; }
    [BindProperty]
    public int ACtemperature { get; set; }
    [BindProperty]
    public int ACpower { get; set; }
    [BindProperty]
    public int ACdirection { get; set; }
    [BindProperty]
    public bool ACopt1 { get; set; }
    [BindProperty]
    public int ACopt2 { get; set; }
    [BindProperty]
    public int ACopt3 { get; set; }

But this is not work with the radiobutton and checkbox. Any idea to solve?

Thanks.




Changing database boolean using html checkboxes

I want to change the value of my database 'Sent' boolean to true when the user clicks a checkbox.

My contact.php so I can edit what I want the message and the subject to be in my website

<?php
    if(isset($_POST['submit'])){
      $to = $_POST['email'];
      $from = "my_email@gmail.com";
      $subject = $_POST['subject'];
      $message = $_POST['message'];

      $headers = "From:" . $from;
      mail($to,$subject,$message,$headers);
      echo "Email sent!";
      }
?>

My index.php, dbh has the connection while the contact.php has the php so I can send emails to several recipients:

<?php
    include_once 'dbh.php';  
    include_once 'contact.php';  
?>

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

</head>

<body>

    <div class="container">
    <br>
    <div class="row justify-content-center">
    <br>
    <table class="scroll">
    <thead>

        <tr>
            <th>Schools Name</th>
           <th>Schools Email</th>
           <th>Sent</th>
        </tr>

    </thead>

    <tbody>
        <?php

            $execItems = $conn->query("SELECT Name,SchoolMail,Sent FROM Schools");

            while($infoItems = $execItems->fetch_array()){
                echo    "
                        <tr>
                            <td>".$infoItems['Name']."</td>
                            <td>".$infoItems['SchoolMail']."</td>
                            <td>".$infoItems['Sent']."</td>
                        </tr>
                    ";

            }
        ?>
    </tbody>
</table>


            <div class="mail">
            <form action="" method="post">
            <button type="button" onclick="emailNext();">Add Email</button>
            <div id="addEmail"></div>

            <script>

            function emailNext() {
            var nextEmail, inside_where;
            nextEmail = document.createElement('input');
            nextEmail.type = 'text';
            nextEmail.name = 'email[]';
            nextEmail.className = 'class_for_styling';
            nextEmail.style.display = 'block';
            nextEmail.placeholder = 'Inserrt your Email';
            inside_where = document.getElementById('addEmail');
            inside_where.appendChild(nextEmail);
            return false;
            }

            </script>

            Subject:<br><textarea rows="1" name="subject" cols="30"></textarea><br>
            Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
            <input type="submit" name="submit" value="Submit">
            </form>
                </form>
            </div>
        </div>
    </div>
</body>

</html>

Is there a way so when a user clicks on a checkbox it sends data to the database and changes its value to true, so the checkbox stays active.




How to post blank array (neither NULL nor "") values in php in no checkbox is checked

Bare me if I am asking something very basic as I am new to php. I have a list of checkboxes and if checked their values are posted to json file which is working fine. When user uncheck all of them I get NULL value in array and if I set its value="" its returns depends :[""]. what i want is if user did not check any checkbox it returns depends:[] only neither NULL nor "". Here is my code.

Linked With

      <input type="checkbox" name="depends[]" value="1"  id="ch2" > 1
      <input type="checkbox" name="depends[]" value="2"  id="ch3" > 2
     <input type="checkbox" name="depends[]" value="3"  id="ch5" > 3
    <input type="checkbox" name="depends[]" value="4"  id="ch6" > 4
    <input type="checkbox" name="depends[]" value="5"  id="ch7" > 5
    <input type="checkbox" name="depends[]" value="6"  id="ch8" > 6
    <input type="checkbox" name="depends[]" value="7"  id="ch9" > 7

in php code i am calling it as

        'depends'=>$_POST['depends']

Thanks in advance for your time and help.




Passing multiple checkbox values to deeper level of model .net mvc

A few similar questions have been asked before but my use case is a bit different.

So this is my model:

  public class YourModel
    {
        public string[] Suburb { get; set; }
    }

And my view:

    <input name="Suburb" type="checkbox" value="sydney" /><span>sydney</span>
    <input name="Suburb" type="checkbox" value="melbourne" /><span>melbourne</span>

Controller:

 public ActionResult AdvancedSearch(YourModel s)
        {
            //logic
        }

So MVC is smart enough to reteive the multiple checkbox values to put them in the Suburb array in YourModel model. I can inspect all values there. But my use case is that the YourModel is just the nested model inside another model MyModel:

  public class MyModel
    {
        //other properties
        public YourModel m { get; set; }
    }

So now How do I make MVC post the checkbox values to a deeper model MyModel.YourModel ? I have tried @Html.CheckBoxFor and @Html.CheckBox but neither of them worked.

Right now my work around is to add a temporary array placeholder in the outside model and then assign all the data to the inside model when available, but that is definitely not ideal.




customize input checkbox color and background in 2018

I need to customize the look and feel of some input checkboxes.

I found this duplicate but the code in the answers have not been updated since 2015

How to style a checkbox using CSS?

Not trying to be picky, but I'm looking for a clean, cross-browser solution, preferably without third party scripts.

<input type="checkbox" class="linksCheckbox" onclick="" 
data-toggle="popover" data-placement="bottom" data-trigger="manual" 
data-html="true" data-content="<ul><li><ul><li><a href='' target='_blank'>test</a></li></ul></li></ul>" 
data-original-title="" title="">

Not sure if I will get in trouble as there are similar questions out there, but they seem quite outdated. Perhaps there has been some developments on this.

enter image description here




mardi 30 janvier 2018

How to validate selected combobox on datagridview?

I am currently making an excel validation program.

I want to validate the selected KPI values under a specific month. Say, the selected KPI column box is "SALES VOLUME" and the checkbox that is checked is "JANUARY", only SALES VOLUME KPI under JANUARY shall be only validated.

Result example should be like this :

A textfile would pop out showing this values on the selected KPI Combo Box and checkbox of the month.

KPI: Sales Volume

Category: Macau & Shipstore

Month: January

Value: 1283091823

Only the KPI SALES VOLUME from the month January shall be validated.

For reference, here's an image of the UI.

My codes are as follows:

From ExcelMethods Class:

This method validates each month depending on the checkbox checked.

 public void Validate_Month(DataGridView dataGridView, int month, int select)
    {
        int kpi = 2;
        int category = 3;
        decimal num;

        FileStream fs = new FileStream(@"C:\brandon\InvalidColumnsByMonth.txt", FileMode.OpenOrCreate, FileAccess.Write);
        StreamWriter sw = new StreamWriter(fs);

        sw.BaseStream.Seek(0, SeekOrigin.End);

        StringBuilder sb = new StringBuilder();
        if (dataGridView.ColumnCount > 3)
        {
            for (int h = select; h <= month; h++)
            {
                for (int i = 0; i < dataGridView.RowCount; i++)
                {
                    if (!Decimal.TryParse(dataGridView[h, i].Value.ToString(), out num))
                    {
                        if (dataGridView[h, i].Value.ToString() == null || dataGridView[h, i].Value.ToString() == "") 
                        {

                        }
                        else
                        {
                            sb.AppendLine("[KPI]: " + dataGridView.Rows[i].Cells[kpi].Value.ToString()); 
                            sb.AppendLine("[Category]: " + dataGridView.Rows[i].Cells[category].Value.ToString());
                            sb.AppendLine("[Month]:" + dataGridView.Columns[h].Name.ToUpper());
                            sb.AppendLine("[VALUE]:  " + dataGridView[h, i].Value.ToString() + "");
                            sb.AppendLine("");

                            sw.WriteLine("[KPI]: " + dataGridView.Rows[i].Cells[kpi].Value.ToString());
                            sw.WriteLine("[Category]: " + dataGridView.Rows[i].Cells[category].Value.ToString());
                            sw.WriteLine("[Month]:" + dataGridView.Columns[h].Name.ToUpper());
                            sw.WriteLine("[VALUE]: {" + dataGridView[h, i].Value.ToString() + "}");
                            sw.WriteLine("");

                        }
                    }
                }
            }

            if (sb.Length != 0 )
            {
                MessageBox.Show(sb.ToString());
                Process.Start(@"C:\brandon\InvalidColumnsByMonth.txt");

            }

            else
            {
                int h = select;

                MessageBox.Show("No errors in month of " + dataGridView.Columns[h].Name + ".");
            }

            sw.Flush();
            sw.Close();

        }
    }

From my Form 1 Class

This is for reference ExcelMethods method, Validate_Month

 public void Validate(CheckBox cb, DataGridView dataGridView1, String month, int i)
    {
        if (cb.Checked == true && dataGridView1.Columns.Contains(month) )
        {
            ExcelMethods.Validate_Month(dataGridView1, 4 + i, 4 + i);
        }
    }

and lastly, from Form 1 Class is the btnValidateAll_MouseClick method

 private void btnValidate_MouseClick(object sender, MouseEventArgs e)
    {
        Validate(checkBox1, dataGridView1, "January", 0);
        Validate(checkBox2, dataGridView1, "February", 1);
        Validate(checkBox3, dataGridView1, "March", 2);
        Validate(checkBox4, dataGridView1, "April", 3);
        Validate(checkBox5, dataGridView1, "May", 4);
        Validate(checkBox6, dataGridView1, "June", 5);
        Validate(checkBox7, dataGridView1, "July", 6);
        Validate(checkBox8, dataGridView1, "August", 7);
        Validate(checkBox9, dataGridView1, "September", 8);
        Validate(checkBox10, dataGridView1, "October", 9);
        Validate(checkBox11, dataGridView1, "November", 10);
        Validate(checkBox12, dataGridView1, "December", 11);

    }




c# WPF radio button only showing checked on mouse over in Server 2012 R2 (gif included)

Using C# with .net 4.6.2

I am getting a strange problem with BOTH check boxes and radio buttons on Server 2012 R2. It works correctly on ANY other OS and also works if I use .net 4.0. They only show they are checked when I mouse over them.

Strange

Here is the XAML code:

                    <RadioButton x:Name="reset_radio" Content="Reset" Foreground="White"
                                 Margin="114,362,0,0" Height="26"
                                 HorizontalAlignment="Left" VerticalAlignment="Top" VerticalContentAlignment="Center"
                                 FontFamily="Segoe UI" FontSize="16" FontWeight="Bold"
                                 GroupName="ModifyUsersRadio"
                                 IsTabStop="False"
                                 IsChecked="{Binding Reset_Checked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

At a total loss here why it would be doing this.




Change checkbox colour in Android

I'm new to Android development and I'm following this tutorial for showing checkbox in Android. Checkbox showing properly.

But I want to change the checkbox color. How can I do this?

Thanks,




Convert AngularJS indeterminate checkbox to Angular 5

I have an AngularJS (1.5) setup for making a parent checkbox indeterminate if one of its children is selected as well as selecting all the children if the parent is selected.

I'm having trouble converting the old ES5 JS to typescript.

Here's the old controller:

  var _this = this;

_this.hierarchicalData = [
  {
    id: 0,
    label: 'Parent item',
    checked: false,
    children: [
      { id: 0, label: 'Child one', value: 'child_one', checked: false },
      { id: 1, label: 'Child two', value: 'child_two', checked: false },
      { id: 2, label: 'Child three', value: 'child_three', checked: false }
    ]
  }
];

_this.selectedChildren = [];
_this.isIndeterminate = false;
_this.allRowsSelected = false;

_this.selectChildren = function (data, $event) {
  var parentChecked = data.checked;
  angular.forEach(_this.hierarchicalData, function (value, key) {
    angular.forEach(value.children, function (value, key) {
      value.checked = parentChecked;
    });
  });
};

_this.selectChild = function (data, $event) {
  if (_this.selectedChildren.indexOf(data.id) === -1) {
    _this.selectedChildren.push(data.id);
    data.selected = true;
  } else {
    _this.selectedChildren.splice(_this.selectedChildren.indexOf(data.id), 1);
    _this.allRowsSelected = false;
    data.selected = false;
  }
};

// for the purposes of this demo, check the second child checkbox
_this.selectedChildren.push(1);
_this.hierarchicalData[0].children[1].checked = true;

and the old template:

 <ul class="list-nomarkers">
  <li ng-repeat="parent in check.hierarchicalData">
    <div class="checkbox">
      <label>
        <input type="checkbox" ng-model="parent.checked" ng-click="check.selectChildren(parent, $event)" ui-indeterminate="check.selectedChildren.length">
      </label>
    </div>
    <ul class="list-nomarkers">
      <li ng-repeat="child in parent.children">
        <div class="checkbox">
          <label>
            <input type="checkbox" ng-model="child.checked" ng-click="check.selectChild(child, $event)"> 
          </label>
        </div>

      </li>
    </ul>
  </li>
</ul>

I updated the template for Angular 5:

   <ul class="list-unstyled">
     <li *ngFor="let parent of hierarchicalData">
      <div class="form-check">
        <input class="form-check-input" type="checkbox" [(ngModel)]="parent.checked" (click)="selectChildren(parent, $event)">
        <label class="form-check-label">
         
        </label>
      </div>
      <ul class="list-unstyled">
        <li *ngFor="let child of parent.children">
          <div class="form-check">
            <input class="form-check-input" type="checkbox" [(ngModel)]="child.checked" (click)="selectChild(parent, $event)">
            <label class="form-check-label">
              
            </label>
          </div>
        </li>
      </ul>
     </li>
   </ul>

And added the 2 main functions to the component:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'pb-ds-checkboxes',
  templateUrl: './checkboxes.component.html'
})
export class CheckboxesComponent implements OnInit {
  hierarchicalData = [
    {
      id: 0,
      label: 'Parent item',
      checked: false,
      children: [
        { id: 0, label: 'Child one', value: 'child_one', checked: false },
        { id: 1, label: 'Child two', value: 'child_two', checked: false },
        { id: 2, label: 'Child three', value: 'child_three', checked: false }
      ]
    }
  ];
  selectedChildren = [];
  isIndeterminate = false;
  allRowsSelected = false;
  constructor() {}

  ngOnInit() {}

  selectChildren = function(data, $event) {
    const parentChecked = data.checked;
    angular.forEach(this.hierarchicalData, function (value, key) {
      angular.forEach(value.children, function (value, key) {
        value.checked = parentChecked;
      });
    });
  };

  selectChild = function(data, $event) {
    if (this.selectedChildren.indexOf(data.id) === -1) {
      this.selectedChildren.push(data.id);
      data.selected = true;
    } else {
      this.selectedChildren.splice(this.selectedChildren.indexOf(data.id), 1);
      this.allRowsSelected = false;
      data.selected = false;
    }
  };
}

Obviously, I need to convert the old angular.forEach into ES6, but I'm still a little weak on arrow functions. Can someone please give me a nudge in the right direction?




Auto add checkbox values and keep their name for storing in database

I have checkboxes retrieved from my database with respective item_name and value which happen to be displayed correctly, but here is my issue, the values are being added/subtracted automatically when selected/checked, however, i want to save the selected check box item_names and also the total sum of the values from the checkboxes. I can't accomplish this because the value option holds numeric data which should have been the checkbox item_name; here is so far what i have.

    <script type="text/javascript">
    function checkTotal() {
        document.listForm.total.value = '';
        var sum = 0;
        for (i=0;i<document.listForm.sel_car.length;i++) {
          if (document.listForm.sel_car[i].checked) {
            sum = sum + parseInt(document.listForm.sel_ca[i].value);
          }
        }
        document.listForm.total.value = sum;
    }
</script>

HTML/PHP Snippet

    <h4>Available Cars | Click on desired car(Multiple Selections enabled) | Total Price: <input type="text" size="2" name="total" value="0"/></h4>
        <div class="form-group">

        <?php

    $stmt = $DB_con->prepare('SELECT * FROM cars ORDER BY car_id DESC');
    $stmt->execute();

    if($stmt->rowCount() > 0)
    {
        while($row=$stmt->fetch(PDO::FETCH_ASSOC))
        {
            extract($row);
            ?>  
        <div class="col-md-3"><label class="btn btn-primary">
            <img src="user_images/<?php echo $row['userPic']; ?>" alt="..." class="img-thumbnail img-check"><input type="checkbox" name="sel_car[]" id="item4" value="<?php echo $row['car_price']; ?>" class="hidden" autocomplete="off"  onchange="checkTotal()"/>
            <h5><?php echo $row['se_car_model']; ?> | UGX <?php echo $row['car_price']; ?>/=</h5>
            </label></div>

<?php
        }
    }
?>

Hope i get some help, kindly don't down vote my question, don't want to be banned




DataTable with several type of checkbox

Am using datatable with checkbox. have serveral checkbox with two type of class name.Need to check all checkbox based on class name

This is my code :-

      var exampless = $('.table1').DataTable({
        responsive: true,
        "searching": false,
        "ordering": false,
        "lengthChange": false,
         "bInfo" : false,
         className: 'select-checkbox',
     });
     $(".alluser").click(function () {
        var cols = exampless.column(0).nodes(),
        state = this.checked;

        for (var i = 0; i < cols.length; i += 1) {
        cols[i].querySelector(".User").checked = state;
        }
     });

Getting this error

TypeError: cols[i].querySelector(...) is null




Working with Spring Form Check boxes to load dynamic view in Freemarker

I have requirement to show check boxes on freemarker page for below requirement-

User will have option to select multiple item from checkbox on Scree1 as demonstrated below -

Screen1 Checkbox Option -
Server1_CheckBoxOpn
Server2_CheckBoxOpn
Server3_CheckBoxOpn

Now Suppose User have selected Server1 And Server2 from Checkbox, Then there will be a database call for each choice and will have to show corresponding output as demonstrated below -

Screen2 Checkbox Option -
Server1
(Intance1_CheckBoxOpn,Intance2_CheckBoxOpn)
Server2

(Intance1_CheckBoxOpn,Intance2_CheckBoxOpn)

Here User can again select multiple option and based on input provided on screen2, I have to do some processing.

I have used freemaker as User Interface. I am facing two issue here-

Screen1 Problem I have used below code in Freemarker to display checkbox and binding with Entity-

<@spring.formCheckboxes path="mwaCatlogueProfile.hostName" options=hostnameMap separator="<br>"/>

Where mwaCatlogueProfile.hostName (String Data Type) is my Entity Field to bind user input with Entity And hostnameMap (HashMap) is Checkbox Option Value.
But by binding String Datatype I am getting user input as String with comma separated value .
When Trying to Bind List DataType FreeMarker is throwing below error -

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'startServerDto' on field 'hostNameList': rejected value [DLVJBSCHIU1087]; codes [typeMismatch.startServerDto.hostNameList,typeMismatch.hostNameList,typeMismatch.java.util.Map,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [startServerDto.hostNameList,hostNameList]; arguments []; default message [hostNameList]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Map' for property 'hostNameList'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Map' for property 'hostNameList': no matching editors or conversion strategy found]
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:115) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]


I want user input from checkbox as list instead of simple String.Since keeping spring binding as String giving me checkbox comma separated value.

Screen2 Problem- I need to display output group wise.To do so, I will have to use ServerName as Key and InstanceName as ListOfValues. I can write this in Java, but don't know how to display in FreeMarker. Please suggest code chuck for same.

Many Thank in advance. Mayank




How to check/uncheck a list of checkboxes in react

I have a room page and in that page I have a list of sensors attached to that room, those sensors can be selected using a checkbox, like so:

<div className="checkboxRowContent">
  {sensors.map(s => {
    return (
      <div className="checkboxElementWrapper" key={s.id}>
        <label htmlFor={`sensor${s.id}`}>
          <div className="checkboxLabel">
            <Link to={`/sensors/edit/${s.id}`}>{s.name}</Link>
          </div>
          <input
            type="checkbox"
            id={`sensor${s.id}`}
            name="sensorId"
            value={s.id}
            checked={s.roomId === values.id}
            onChange={handleCheckbox}
          />
          <span className="checkbox" />
        </label>
      </div>
    );
  })}
</div>

the problem is - this approach prohibits me from unchecking the checkbox (so if in db that sensor is attached to that room - that's it). How could I rewrite this so that I can check/uncheck this checkbox?




Dynamic checkbox in Java

I am working on a Java project and I was thinking of a way to check some inputs.

I will communicate with my database and the response will be the number of wrong telephone numbers.

What I would like to do is to read the response and create a checklist where I will list the number of wrong telephones.

For instance, if my database returns 2 wrong numbers I would like to create two checkbox and ask the users whether they fixed it or not.

Can you also suggest me a way to save this response. Will it be better to save it as a simple string or as a JSON?




lundi 29 janvier 2018

Making additional elements required

I am creating a form submission; some of the elements are required so are not. I have a check box in the form that will make additional elements visible if the box is checked. I am using html and javascript.

The problem I am currently having is that when I hit submit the elements that are invisible are still required (I will attach my code). I want to make it where the additional elements are required only when the box is checked.
I am not sure how to write the javascript or jquery to make this possible.

Any help is appreciated! Thank you.

        function addPerson (box) {
        
        var chboxs = document.getElementsByName("person");
        var vis = "none";
        for(var i=0;i<chboxs.length;i++) { 
            if(chboxs[i].checked){
             vis = "block";
                break;
            }
        }
        document.getElementById(box).style.display = vis;
    }
<html>
<form>
*Name: <input size=27 type="text" name="mfname" required><br>
*Email: <input size=27 type="text" name="mfname" required><br>
*Date: <input size=27 type="text" name="mfname" required><br>

<input type="checkbox" name="person" value="on" onclick="addPerson('person')">Add another person<br>

<div id="person"  style="display:none">
*Name: <input size=27 type="text" name="mfname" required><br>
*Email: <input size=27 type="text" name="mfname" required><br>
*Date: <input size=27 type="text" name="mfname" required><br>
</div>

<button type="submit" value="Submit">Submit</button>
</form>
</html>



MDL Tables Selectable not working as expected

I'm using Material Design Lite and trying to implement a basic data table with the code below:

<table class="mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp">
  <thead>
    <tr>
      <th class="mdl-data-table__cell--non-numeric">Material</th>
      <th>Quantity</th>
      <th>Unit price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="mdl-data-table__cell--non-numeric">Acrylic (Transparent)</td>
      <td>25</td>
      <td>$2.90</td>
    </tr>
    <tr>
      <td class="mdl-data-table__cell--non-numeric">Plywood (Birch)</td>
      <td>50</td>
      <td>$1.25</td>
    </tr>
    <tr>
      <td class="mdl-data-table__cell--non-numeric">Laminate (Gold on Blue)</td>
      <td>10</td>
      <td>$2.35</td>
    </tr>
  </tbody>
</table>

The table generates fine, but the above code does not generate the checkboxes that I need. Based on the documentation mdl-data-table--selectable should generate the checkboxes, but they are not showing up. I did some digging around and found this article on github: https://github.com/google/material-design-lite/wiki/Deprecations.

While this is a bit disappointing, I copied their example just to see if it generates the checkboxes correctly. My exact code is below:

<html>
  <head>
    <!-- Material Design Lite -->
    <script src="https://storage.googleapis.com/code.getmdl.io/1.0.5/material.min.js"></script>
    <link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.5/material.indigo-pink.min.css">
    <!-- Material Design icon font -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  </head>
  <body>


    <table class="mdl-data-table mdl-shadow--2dp">
  <thead>
    <tr>
      <th>
          <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" for="table-header">
            <input type="checkbox" id="table-header" class="mdl-checkbox__input" />
          </label>
      </th>
      <th class="mdl-data-table__cell--non-numeric">Material</th>
      <th>Quantity</th>
      <th>Unit price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
       <td>
          <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" for="row[1]">
            <md-checkbox type="checkbox" id="row[1]" class="mdl-checkbox__input" />
          </label>
      </td>
      <td class="mdl-data-table__cell--non-numeric">Acrylic (Transparent)</td>
      <td>25</td>
      <td>$2.90</td>
    </tr>
    <tr>
       <td>
          <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" for="row[2]">
            <input type="checkbox" id="row[2]" class="mdl-checkbox__input" />
          </label>
      </td>
      <td class="mdl-data-table__cell--non-numeric">Plywood (Birch)</td>
      <td>50</td>
      <td>$1.25</td>
    </tr>
    <tr>
      <td>
          <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" for="row[3]">
            <input type="checkbox" id="row[3]" class="mdl-checkbox__input" />
          </label>
      </td>
      <td class="mdl-data-table__cell--non-numeric">Laminate (Gold on Blue)</td>
      <td>10</td>
      <td>$2.35</td>
    </tr>
  </tbody>
</table>  
  </body>
</html>

I've included all the necessary links to the JS and CSS file, but what returns looks like this:

enter image description here

For consistency, I really need the checkboxes to have the Material Design look/feel, but this looks like Bootstrap. Any ideas what's going on here?




TABLE HTML -> How can I change the way it is done?

I am trying to make a table with checkboxes on every row of the table.

I got an example(Code Example link), but I am not being able to get it done. I do not want to use the "data-url" as a source of the table. Except that, everything is accordingly with what I need.

I want to feed the "tbody" by myself.

Here is the example I am following: Code Example

What I want to accomplish:

<tbody>
    <tr>
        <!-- I do not know what to put over here in order to get it working-->
        <td data-field="state" data-checkbox="true"></th>
        <td>Foo</td>
        <td>666</td>
        <td>6969</td>
        <td>Let there be rock</td>
    </tr>
</tbody>




Property set when leave page

I have a CheckBox in a TabControl.
I bound the property Checked like this :

MyCheckBox.DataBindings.Add("Checked", MyBindingSource, "IsOn", true, DataSourceUpdateMode.OnPropertyChanged);

Property isOn :

public bool IsOn
{
    get
    {
        return _isOn;
    }
    set
    {
        bool someCondition;
        // a test is done
        if (value != _isOn && someCondition)
        {
            _isOn = value;
        }
        else
        {
            System.Windows.Forms.MessageBox.Show("Condition not OK");
        }
    }
}

When user click on the CheckBox, when someCondition is false, a message box is displayed and the CheckBox does not change.

My problem is when user changes page in TabControl, the message is displayed. I saw with debugger that when page changes in TabControl, property is set to the last value tried.

What can I do to not display a MessageBox when changing page?




check if all inputs are checked

I have 2 buttons and 2 inputs. The "buy"-button should only fire its default function when both inputs are checked. If not it should mark them with a red border. What am I doing wrong here?

jQuery(function($) {
        $('.checkedterms:checked').length == $('.abc').length
        $("#upsellyes").click(function(e) {
                $(".checkedterms").change(function(){
                        if ($('.checkedterms:checked').length == $('.checkedterms').length) {
                                e.preventDefault();
                                $("#terms-required").addClass('invalid');
                        } 
                        else {
                                $("#terms-required").removeClass('invalid');
                        }
                });
        });
});
.invalid {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="invalid">
<input type="checkbox" class="checkedterms" name="terms" id="terms" style="position: absolute;"><label for="terms" class="checkbox" style="display: inline-block!important;font-weight:normal!important;margin-left: 25px;">I have read <a href="#" >Allgemeinen Geschäftsbedingungen</a>.<span class="required">*</span></label><br />
<input type="checkbox" class="checkedterms" name="terms" id="terms" style="position: absolute;"><label for="terms" class="checkbox" style="display: inline-block!important;font-weight:normal!important;margin-left: 25px;">I have read <a href="#" >Widerrufsbelehrung</a>.<span class="required">*</span></label><br />
</div><br>
<a href="#" id="upsellyes">buy</a><br><br>
<a href="#">no thanks</a>



Pre-Selected Checkbox

I have a problem with pre select a checkbox when opening the form:

<h:selectManyCheckbox id="ereignistyp" label="Ereignistyp"
                                collectionType="java.util.ArrayList"
                                value="#{uebergreifendeEreignisListQuerySpec.criterionMap['ereignistyp'].values}">
                                <f:converter converterId="criterionValueConverter" />
                                <f:selectItems
                                    value="#{d:enumsToSelectItems(uebergreifendeEreignisListQuerySpec.criterionMap['ereignistyp'].predefinedValues)}" />
                            </h:selectManyCheckbox>

uebergreifendeEreignisListQuerySpec.criterionMap['ereignistyp'].values is empty

while

uebergreifendeEreignisListQuerySpec.criterionMap['ereignistyp'].predefinedValues has [HFEHLER, PROTOKOLLEINTRAG, MAENGEL, HSONSTIGES, HALARM]

Even when manually define uebergreifendeEreignisListQuerySpec.criterionMap['ereignistyp'].values to values, the checkbox won't select but interal it is properly used and filtered.




function not been detected on unchecking of checkbox

i have a checkbox that when i check it,it redirects to another function as follows

function Allchecks1(event) {
            event.stopPropagation();
            var market = $(event.target).closest('a');
            var destination = market.attr('data-destination');
            if ((destination == 'null' || destination == 'local') && market.attr('dataid')) {
                var id = market.attr('dataid');
                navigateToEvent(id); // passes the id to this function
                return true;   
            }
            else if (!$('cb').is(':checked')) {
                alert("owiedjiej");     //did a test when i uncheck the textbox nothing happends
            }  
        }

function navigateToEvent(id) {
            var url = '/' + 'List/events/';
            if (id)
                url += id;
        }

the above passes the Id to navigateToEvent function so the output for example is as follows,

/List/events/1111

what i am trying to achieve is that when i untick the check box the id should be removed and my expected output should be

/List/events/

How do i achieve this? i added an alert just for testing purposes on the unticking of the checkbox and it doesnt fire any alerts.

html

<li "><a  data-destination="local" dataid="' + this.MarketID + '" data-nodeid = "' + this.NodeId + '" ><span><input type="checkbox" id="cb" onclick=Allchecks1(event);></span></a></li>');




In an existing DataGridView, replace textual header of one column with a checkbox (for sorting capabilities)

I need to replace textual header of a column in an existing DataGridView. With this checkbox I will then control sorting of the values in cells below.

I tried:

DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.TrueValue = true;
checkBoxColumn.FalseValue = false;
checkBoxColumn.Width = 80;

but this just gave me checkbox in cells.




dimanche 28 janvier 2018

How to call an activity after click checkbox

I'm new in android studio and this is my first time using checkbox.I have a fragment (Auto_Billing_Postpaid_Fragment) and an activity(AutoBillingActivity).I have checkbox with id name "checkbox_auto_billing" in fragment.Supposedly, after click in checkbox,it will open AutoBillingActivity .but after check the box,the activity did not open.I'd followed some similar tutorials but didn't work.What is wrong with my code or anything I missed?

Auto_Billing_Postpaid_Fragment :

@Override
public void onClick(View v) {

    CheckBox checkbox_auto_billing = (CheckBox)v.findViewById(R.id.checkbox_auto_billing);
    Intent intent = new Intent(getActivity(), AutoBillingActivity.class);
    startActivity(intent);
}

AutoBillingActivity :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_auto_billing);
    Intent intent= getIntent();
}




Check boxes and combined text output

I need help with code for a combined text box output.

enter image description here

A. Input: The user should choose among different checkbox options.

B. Output: The selected text strings should go collectively to an updated text box. The textbox should update instantly as the checkboxes are selected, so you will se the final result directly.

C. Transfer: By clicking a button the content of the text box should copy to memory for later insertion in other software.

Any suggestions?




Expandablelistview with checkboxes change selected checkboxes

I have an Expandablelistview that I load from database some data and I put that data in with checkboxes, but the problem is, if I check something on group 1 and open group 0, the checked checkbox at group 1 become unchecked and the last checkbox at group 0 become checked.

Group 0

Group 1

My adapter:

public class ExpandableListCheckboxAdapter extends BaseExpandableListAdapter {
    private List<String> listFather;
    private HashMap<String, ArrayList<CheckBox>> listChildren;
    private LayoutInflater inflater;
    private SparseBooleanArray spa = new SparseBooleanArray();

    public ExpandableListCheckboxAdapter(Context context, List<String> listGroup, HashMap<String, ArrayList<CheckBox>> listData){
        this.listFather = listGroup;
        this.listChildren = listData;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

    @Override
    public int getChildrenCount(int groupPosition) {
        return listChildren.get(listFather.get(groupPosition)).size();
    }

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

    public String getGroupText(int groupPosition) {
        return listFather.get(groupPosition).toString();
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return listChildren.get(listFather.get(groupPosition)).get(childPosition);
    }

    public String getChildText(int groupPosition, int childPosition) {
        return listChildren.get(listFather.get(groupPosition)).get(childPosition).getText().toString();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }


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

    public boolean isChecked(int groupPosition, int childPosition) {
        return listChildren.get(listFather.get(groupPosition)).get(childPosition).isChecked();
    }


    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        ViewHolderGroup holder;

        if(convertView == null){
            convertView = inflater.inflate(R.layout.expandable_father, null);
            holder = new ViewHolderGroup();
            convertView.setTag(holder);

            holder.txvFatherList = (TextView) convertView.findViewById(R.id.txvFatherList);
        }
        else{
            holder = (ViewHolderGroup) convertView.getTag();
        }

        holder.txvFatherList.setText(listFather.get(groupPosition));

        return convertView;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) {
        String val = (String) getChildText(groupPosition, childPosition);
        final ExpandableListCheckboxAdapter.ViewHolderItem holder;

        if(convertView == null){
            convertView = inflater.inflate(R.layout.expandable_children_subject, null);
            holder = new ExpandableListCheckboxAdapter.ViewHolderItem();
            convertView.setTag(holder);
            holder.ckbChildrenSub = (CheckBox) convertView.findViewById(R.id.ckbChildrenSub);
            holder.ckbChildrenSub.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if(holder.ckbChildrenSub.isChecked()){
                        if(universalVariables.subjects.containsKey(getGroupText(groupPosition))){
                            List<String> aux = new ArrayList<>();
                            aux = universalVariables.subjects.get(getGroupText(groupPosition));
                            if(!aux.contains(holder.ckbChildrenSub.getText().toString()))
                                aux.add(holder.ckbChildrenSub.getText().toString());
                            universalVariables.subjects.put(getGroupText(groupPosition), aux);
                        }
                        else{
                            List<String> aux = new ArrayList<>();                 
                            aux.add(holder.ckbChildrenSub.getText().toString());
                            universalVariables.subjects.put(getGroupText(groupPosition), aux);
                        }
                    }
                    else {
                        if (universalVariables.subjects.containsKey(getGroupText(groupPosition))) {
                            List<String> aux = new ArrayList<>();
                            aux = universalVariables.subjects.get(getGroupText(groupPosition));
                            if (aux.contains(getChildText(groupPosition, childPosition))) {
                                aux.remove(getChildText(groupPosition, childPosition));
                                universalVariables.subjects.put(getGroupText(groupPosition), aux);
                            }
                        }
                    }
                }
            });
        }
        else{
            holder = (ExpandableListCheckboxAdapter.ViewHolderItem) convertView.getTag();
        }

        holder.ckbChildrenSub.setText(val);

        return convertView;
    }

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

    class ViewHolderGroup {
        TextView txvFatherList;
    }

    class ViewHolderItem {
        CheckBox ckbChildrenSub;
    }
}

Method to load data from database:

private void loadSubjects(){
    //Use database
    for (int i = 0; i < disciplinas.size(); i++) {
        if (!listGroup.contains(disciplinas.get(i)))
            listGroup.add(disciplinas.get(i));
        int idGeneric = 0;
        ArrayList<CheckBox> auxList = new ArrayList<CheckBox>();
        databaseHelper = dbHelper.getInstance(this, DB_NAME);
        String generic = disciplinas.get(i);
        String query = "SELECT Assunto FROM Assunto WHERE Disciplina='" + generic + "'";
        Cursor c1 = databaseHelper.rawQuery(query);
        if (c1 != null && c1.getCount() != 0) {
            if (c1.moveToFirst()) {
                do {
                    String assunto = c1.getString(c1.getColumnIndex("Assunto"));
                    checkbox = new CheckBox(this);
                    checkbox.setText(assunto);
                    auxList.add(checkbox);
                    idGeneric = idGeneric + 1;
                } while (c1.moveToNext());
            }
        }
        if (c1 != null)
            c1.close();
        listData.put(disciplinas.get(i), auxList);
    }

    expCheckListView = (ExpandableListView) findViewById(R.id.elstvSub);
    checkAdapter = new ExpandableListCheckboxAdapter(Assuntos.this, listGroup, listData);
    expCheckListView.setAdapter(checkAdapter);
}

Children XML:

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

    <CheckBox
        android:id="@+id/ckbChildrenSub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Father XML:

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

    <TextView
        android:id="@+id/txvFatherList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:textSize="18dp"
        android:layout_marginLeft="33dp" />

</LinearLayout>




jQuery - exclusive input checkboxes - enable to uncheck by clicking on current checked input

I did an exclusive menu of 2 input checkboxes on the following link :

exclusive checkboxes

As you can see, each input checkbox corresponds to a different case : (Player Vs Computer) and (Player1 Vs Player2) and each case is associated to 2 buttons (which work as I want).

My issue is that I would like to add a functionality, i.e enable to uncheck the current checkhed box by clicking on the current checkbox (this one which is already checked).

For the moment, I have to click directly on the other input checkbox to uncheck the current one; I would like to get the both functionalities.

Here's the current code which handles these 2 exclusive input checkbox :

// Check input checked
 checkBoxState = $('#'+gameType+'').find('.game').prop('checked');
// Set oneButtonClicked to no for restore
 $('#formGame').prop('oneButtonClicked', 'no');
 // Handling input.game
 $('#'+gameType+'').find('.game').prop('checked', !checkBoxState);
 //$('#'+gameType+'').siblings().find('.game').prop('checked', checkBoxState);
 // Set pointer-events to all for formGame
 $('#formGame').css('pointer-events', 'all');
 // Handling button.btn
 $('#'+gameType+'').find('.btn').css('pointer-events', 'none');
 $('#'+gameType+'').siblings().find('.btn').css('pointer-events', 'all');
 $('#'+gameType+'').find('.btn').prop('disabled', checkBoxState);
 $('#'+gameType+'').siblings().find('.btn').prop('disabled', !checkBoxState);

gameType is the current type of game (Player Vs Computer or Player1 Vs Player2).

input.game represent the input checkboxes

button.btnrepresent the 2 buttons available for each ìnput.game.

If someone could tell me how to add this functionality, i.e unchek by clicking on current checked ,or unchek by clicking directly on the other checkbox ...

Feel free to ask me further informations about this issue.

Thanks in advance




how to open an html popup when the user clicks a checkbox in a tsp page

Do you know how to open an html popup screen by using javascript when the user checks the checkbox in a jsp page ?

If required, i can provide code.

Thanks




how to add check (and uncheck) all box

I have a dynamic table that displays rows that can be checked based off different search criteria. So, the rows that can be checked always change based off the search criteria (meaning, the rows in the table that can be checked are not static).

The main website code is PHP. Any help is much appreciated!

Thanks!




ruby on rails multiple checkbox params

I have an application in which multiple checkboxes to be selected, so how to provide the name as an array in checkbox tag so that I can retrieve it in my params in controller. I am actually quite confused in my checkbox params, especially for multiple checkboxes. can I give it any random name in checkbox name = "any name " so that i can access it in my params in controller Please heed my query, I can't even find an appropriate article for the same

Thanks in advance

I named it as hi[] array, 'hi' random word or should I have to follow some convention

<input type="checkbox" name= "hi[]" value="" class="form-select form-control" id="clients"
                           onchange="this.value=this.checked;"  style="display: inline-block;width: 20px;" />




Selenium Webdriver - How to select checkbox, if it has no id?

So i have this Google Docs survey and there are Checkboxes which i want to check with Selenium Webdriver automatically.

I as usually tried to locate the element id oder the name of it via the editor mode on google chrome, but i simple do not find the id of the checkbox, only the corresponding class name.

<label class="docssharedWizToggleLabeledContainer 
freebirdFormviewerViewItemsRadioChoice"><div class="exportLabelWrapper"><div 
class="quantumWizTogglePaperradioEl docssharedWizToggleLabeledControl 
freebirdThemedRadio freebirdThemedRadioDarkerDisabled 
freebirdFormviewerViewItemsRadioControl" jscontroller="EcW08c" 
jsaction="click:cOuCgd; mousedown:UX7yZ; mouseup:lbsD7e; mouseleave:JywGue; 
touchstart:p6p2H; touchmove:FwuNnf; 
touchend:yfqBxc(preventMouseEvents=true|preventDefault=true); 
touchcancel:JMtRjd; focus:AHmuwe; blur:O22p3e; keydown:I481le; 
contextmenu:mg9Pef" jsshadow="" aria-label="Männlich" tabindex="0" data-
value="Männlich" aria-describedby="  i5" role="radio" aria-checked="false" 
aria-posinset="1" aria-setsize="3"><div class="quantumWizTogglePaperradioInk 
exportInk"></div><div class="quantumWizTogglePaperradioInnerBox"></div><div 
class="quantumWizTogglePaperradioRadioContainer"><div 
class="quantumWizTogglePaperradioOffRadio exportOuterCircle"><div 
class="quantumWizTogglePaperradioOnRadio exportInnerCircle"></div></div>
</div></div><div class="docssharedWizToggleLabeledContent"><div 
class="docssharedWizToggleLabeledPrimaryText"><span dir="auto" 
class="docssharedWizToggleLabeledLabelText exportLabel 
freebirdFormviewerViewItemsRadioLabel">Männlich</span></div></div></div>
</label>
<div class="quantumWizTogglePaperradioRadioContainer"><div 
class="quantumWizTogglePaperradioOffRadio exportOuterCircle"><div 
class="quantumWizTogglePaperradioOnRadio exportInnerCircle"></div></div>
</div>

"Männlich" is here just the text of a label which belongs to the checkbox i want to mark, but not the checkbox as an element by itself.

I hope some of you have some suggestions how to implement the method

driver.findElement(By.name("name"))
driver.findElement(By.id("id"))

in this case. Or should i try something else?

Thanks already for everyone thinking about an awnser!




How to save checkboxes states from a listview for four differents array of Strings

I have a project to manage if the football freestyler landed a trick, like TVShowTime app but with tricks. I have a Custom Adapter for the Listview and four arrays of Strings, I don't know how to save the checkboxes states for each trick.

The checkbox state was configured inside the CustomAdapter0.

Other problem that I'm having is that the checkboxes needs to be pressed twice to change, after you pressed twice if works ok. I have no idea how to fix this.

ListView and checkboxes

CustomAdapter

public class CustomAdapter0 extends BaseAdapter {

    public CustomAdapter0(String[] tricks, Context context) {
        this.tricks = tricks;
        this.context = context;
    }

    private String[] tricks;
    private Context context;
    private boolean isClicked;
    private LayoutInflater layoutInflater;

    @Override
    public int getCount() {
        return tricks.length;
    }

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

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

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {

        View row = convertView;

        if(convertView == null){

            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.custom_listview_tricks, null);
        }

        TextView textView = row.findViewById(R.id.name_xml);
       final ImageButton imageButton = row.findViewById(R.id.unmastered_xml);

        textView.setText(tricks[i]);
        imageButton.setBackgroundResource(R.drawable.unmastered);

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

                if (isClicked) {
                    imageButton.setBackgroundResource(R.drawable.mastered);
                } else {
                    imageButton.setBackgroundResource(R.drawable.unmastered);
                }
                isClicked = !isClicked;
            }
        });

        return row;
    }
}

TricksActivity

public class TricksActivity extends AppCompatActivity {

    private String[] lower = {

            "ATW - Around the World",
            "HTW - Hop the World",
            "Crossover",
            "Crossover 360",
            "Simple Crossover",
            "Reverse Crossover",
            "KATW - Knee Around the World",
            "KHTW - Knee Hop the World",
            "Toe Bounce",
            "Reverse Toe Bounce",
            "Air Jester",
            "ATL - Around the Leg",
            "Hell Juggles",
            "AATW - Abbas Around the World",
            "HATW - Half Around the World",
            "TATW - Touzani Around the World",
            "MATW - Mitchy Around the World",
            "ATATW - AlternateTouzani Around the World",
            "AMATW - Alternate Mitchy Around the World",
            "HMATW - Homie Mitchy Around the World",
            "HTATW - Homie Touzani Around the World",
            "KAATW - Knee Abbas Around the World",
            "KMATW - Knee Mitchy Around the World",
            "KTATW - Knee Touzani Around the World",
            "LEBATW - Lebioda Around the World",
            "LATW - Lemmens Around the World",
            "MAATW - Mitchy Abbas Around the World",
            "RATW - Ratinho Around the World",
            "ATL - Around the Leg",
            "360 ATW",
            "Clipper",
            "JATOW - Joshua Around the Oppositive World",
            "Sagami Aroudn the World",
            "YATW - Yosuke Around the World",
            "Timo ATW",
            "Knee Timo ATW",
            "Air Jester",
            "Eclipse",
            "Half New Shit",
            "ALATW - Alternate Lemmens Around the World",
            "BATW - Beck Around the World",
            "HJATW - Homie Jay Around the World",
            "HMAATW - Homie Mitchy Abbas Around the World",
            "HTAATW - Homie Touzani Abbas Around the World",
            "KAMATW - Knee Alternate Mitchy Around the World",
            "KATATW - Knee Alternate Touzani Around the World",
            "KMAATW - Knee Mitchy Alternate Around the World",
            "LAATW - Lemmens Abbas Around the World",
            "LMATW - Lemmens Mitchy Around the World",
            "LTATW - Lemmens Touzani Around the World",
            "Magellan",
            "New Shit",
            "Palle Trick",
            "Reverse Palle Trick",
            "Toe Stall",
            "Hell Stall",
            "Knee Stall",
            "Hell Juggles",
            "Spin Magic",
            "MichRyc Move",
            "AHMATW - Alternate Homie Mitchy Around the World",
            "AHTATW - Alternate Homie Touzani Around the World",
            "ALMATW - Alternate Lemmens Mitchy Around the World",
            "KLAATW - Knee Lemmens Abbas Around the World",
            "SATW - Skora Around the World",
            "Skora Move",
            "RSATW - Reverse Skora Around the World",
            " HTLATW - Homie Touzani Lemmens Around the World",
            "SZATW - Szymo Around The World",
            "EATW - Eldo Around the World",
            "SKATW - Skala Around the World",
            "ZATW - Zegan Around the World",
            "K3EATW - K3vin Eldo Around the World",
            "SKMATW - Skala Mitchy Around the World",
            "EMATW - Eldo Mitchy Around the World",
            "AEATW - Alternate Eldo Around the World",
            "PATW - Palle Around the World",
            "PMATW - Palle Mitchy Around the World",
            "APATW - Alternate Palle Around the World"

    };

    private String[] upper = {

            "Head Stall",
            "Top Head Stall",
            "Side Head Stall",
            "Shoulder Stall",
            "Neck Stall",
            "360",
            "Chest Stall",
            "ATM - Around The Moon",
            "Carousel",
            "Pavel Roll",
            "LIP Stall",
            "Arm Roll",
            "Nose Stall",
            "Neck Flick",
            "LATM - Luki Around the Moon",

    };
    private String[] sitDown = {

            "Shin Stall",
            "Sole Stall",
            "Abdullah",
            "Sole Juggle",
            "Shin ATW",
            "Dimetto"

    };
    private String[] combosFamosos= {

            "CNK NT Combo",
            "Skóra NT Combo",
            "Palle Combo",
            "Palle Combo 2"

    };

    private ImageView imageView;


    private int codigo;
    ListView listView;

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

        Intent intent = getIntent();
        codigo = intent.getIntExtra("codigo", 0);

        //Toast.makeText(this, ""+codigo, Toast.LENGTH_SHORT).show();

        listView = findViewById(R.id.listview_xml);


        if (codigo == 0){
            CustomAdapter0 customAdapter0 = new CustomAdapter0(lower, TricksActivity.this);
            listView.setAdapter(customAdapter0);

        }if (codigo == 1){

            CustomAdapter0 customAdapter0 = new CustomAdapter0(upper, TricksActivity.this);
            listView.setAdapter(customAdapter0);

        }if (codigo == 2){

            CustomAdapter0 customAdapter0 = new CustomAdapter0(sitDown, TricksActivity.this);
            listView.setAdapter(customAdapter0);

        }if (codigo == 3){

            CustomAdapter0 customAdapter0 = new CustomAdapter0(combosFamosos, TricksActivity.this);
            listView.setAdapter(customAdapter0);

        }if (codigo == 4){


        }

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

                Intent intent = new Intent(getApplicationContext(), VideoActivity.class);

                if(codigo == 0){

                    //Toast.makeText(TricksActivity.this, ""+lower[i], Toast.LENGTH_SHORT).show();
                    intent.putExtra("trick", lower[i]);

                }
                if(codigo == 1){

                    //Toast.makeText(TricksActivity.this, ""+upper[i], Toast.LENGTH_SHORT).show();
                    intent.putExtra("trick", upper[i]);

                }
                if(codigo == 2){

                    //Toast.makeText(TricksActivity.this, ""+sitDown[i], Toast.LENGTH_SHORT).show();
                    intent.putExtra("trick", sitDown[i]);

                }
                if(codigo == 3){

                   //Toast.makeText(TricksActivity.this, ""+combosFamosos[i], Toast.LENGTH_SHORT).show();
                    intent.putExtra("trick", combosFamosos[i]);

                }
                startActivity(intent);
                }

            });

    }

}




pre populate checkbox in a loop VBscript

I am trying to pre populate the check boxes in a DO loop. The values from the querystring are matched with the value from database. But in this case, all checkboxes are checked irrespective of any querystring value. The VBscript code is given below:

<%
Do While NOT RS.EOF

Designchk=Request.QueryString("Designer")
Designchk2=RS("Brand")

if instr(Designchk,DesignchkP2) then
chkd="checked" 
end if

ListL= ListL & vbCrLf & "<li><label class='contR'>" & Designchk2 & "<input type='checkbox' " &  chkd & " name='Designer' value=" & Designchk2 & "></label></li>"
RS.MoveNext
Loop
%>




samedi 27 janvier 2018

jquery file upload check box from

I am a beginner in JS and I decided to use this library: https://blueimp.github.io/jQuery-File-Upload/

My issue is the following :

I have to send (in FormData, thus additional form) the value of 2 checkboxes. The concern is that the checkboxes are false when the page loads and the client changes its value, and in my code, the formdata takes the value of both checkboxes but without updating them during changes (checked / unchecked).

$(function() {
    "use strict";
    var e = $("<button/>").addClass("intimity-button-dark").prop("disabled", !0).text("Processing...").on("click", function() {
        var param1 = $('#guest').is("checked");
        console.log(param1);
        var e = $(this),a = e.data();
        e.off("click").text("Abort").on("click", function() {
            e.remove(), a.abort()
        }), a.submit().always(function() {
            e.remove()
        })
    });
    $("#fileupload").fileupload({
        url: "/server/php/",
        dataType: "json",
        autoUpload: !1,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png|mov|mp4|avi)$/i,
        maxFileSize: 5e6,
        disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
        previewMaxWidth: 200,
        previewMaxHeight: 300,
        formData: {guest: $("#guest").prop('checked'), signed : $("#signed").prop('checked')},
        previewCrop: !0
    }).on("fileuploadadd", function(a, n) {
        n.context = $("<div/>").addClass('col-xs-6 col-sm-4').appendTo("#files"), $.each(n.files, function(a, t) {
            var r = $("<p/>").append($("<span/>").text(t.name));
            a || r.append("<br>").append(e.clone(!0).data(n)), r.appendTo(n.context)
        })
    }).on("fileuploadprocessalways", function(e, a) {
        var n = a.index,
            t = a.files[n],
            r = $(a.context.children()[n]);
        t.preview && r.prepend("<br>").prepend(t.preview), t.error && r.append("<br>").append($('<span class="text-danger"/>').text(t.error)), n + 1 === a.files.length && a.context.find("button").text("Upload").prop("disabled", !!a.files.error)
    }).on("fileuploadprogressall", function(e, a) {
        var n = parseInt(a.loaded / a.total * 100, 10);
        $("#progress .progress-bar").css("width", n + "%")
    }).on("fileuploaddone", function(e, a) {
        $.each(a.result.files, function(e, n) {
            if (n.url) {
                var t = $("<a>").attr("target", "_blank").prop("href", n.url);
                $(a.context.children()[e]).wrap(t)
            } else if (n.error) {
                var r = $('<span class="text-danger"/>').text(n.error);
                $(a.context.children()[e]).append("<br>").append(r)
            }
        })
    }).on("fileuploadfail", function(e, a) {
        $.each(a.files, function(e) {
            var n = $('<span class="text-danger"/>').text("File upload failed.");
            $(a.context.children()[e]).append("<br>").append(n)
        })
    }).prop("disabled", !$.support.fileInput).parent().addClass($.support.fileInput ? void 0 : "disabled")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Add files...</span>
<input id="fileupload" style="display:none;" type="file" name="files[]" multiple>

<input type="checkbox" id="guest" name="guest" value="1">
<input type="checkbox" id="signed" name="signed" value="1">

So, how can I make the "format" retrieve the current values?




Set checkbox as checked after radio button selection

For the beginning, I've Form that includes:

  • Three radio button (id: a-option,b-option,c-opion),
  • One Checkbox (id: optional),

and i would like to achieve that Checkbox can be selected manually as usual, but also the two of them should mark checkbox as selected automatically and disable possibility of unchecking it (let's say that will be b-option and c-option). How should i do that with JS or JQuery.




Checkbox checked or unchecked javascript

I am trying to check and see if the checkbox is checked or unchecked, however when I use element.value it is always returning false for whatever reason... I've tried to use onclick as well. I also printed out the value of element to the console to see if I can tell if the value changes, but couldn't really tell when the checkbox is true or not. Any help is great! Thanks in advance! It keeps going into the else block for whatever reason.

HTML

<div class="form-check">
    <input class="form-check-input" type="checkbox" value="" onchange="javascript:addFilter(event,'freshman');">
    <label class="form-check-label" for="defaultCheck1">Freshman</label>
</div>
<script>
    function addFilter(element,string) {
      let filter_array =[];
      if(element.value){
      if(string =="freshman"){
        filter_array.push(string);
        console.log("Add Freshman to Array");
      }
      if(string =="sophmore"){
        filter_array.push(string);
        console.log("Add Junior to Array");
      }
      if(string =="junior"){
        filter_array.push(string);
        console.log("Add junior to Array");
      }
      if(string =="senior"){
        filter_array.push(string);
        console.log("Add Senior from to Array");
      }

    }

else {

      if(string =="freshman"){
        filter_array.push(string);
        console.log("Remove Freshman from Array");
        console.log(element);
      }
      if(string =="sophmore"){
        filter_array.push(string);
        console.log("Remove Junior from Array");
      }
      if(string =="junior"){
        filter_array.push(string);
        console.log("Remove junior from Array");
      }
      if(string =="senior"){
        filter_array.push(string);
        console.log("Remove Senior from Array");
      }
    }
}
  </script>




Laravel Blade loop error checkboxes with repeated entried

I'll try and go straight to the problem.

I've got a group of checkboxes which are based on items in my database, it's categories table, basically I'm trying to loop all the existent categories in my database and then check if the current one matches a category already in it, if so, echo out a checked checkbox, if not, just an unchecked checkbox.

Everything seems to work fine until I add more than two categories (which ofcourse are related to articles in the db), at that point more categories than needed are echoed out.

Output:

<div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_faccio-quello-che-voglio" value="Faccio quello che voglio" name="categories[]">
                                  <label class="form-check-label" for="category_ faccio-quello-che-voglio">Faccio quello che voglio</label>

                                </div>




                                                                <div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_faccio-quello-che-voglio" value="Faccio quello che voglio" name="categories[]">
                                  <label class="form-check-label" for="category_ faccio-quello-che-voglio">Faccio quello che voglio</label>

                                </div>





                                                                <div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_informatica-giornaliera" value="Informatica Giornaliera" name="categories[]" checked>
                                  <label class="form-check-label" for="category_ informatica-giornaliera">Informatica Giornaliera</label>

                                </div>




                                                                <div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_informatica-giornaliera" value="Informatica Giornaliera" name="categories[]">
                                  <label class="form-check-label" for="category_ informatica-giornaliera">Informatica Giornaliera</label>

                                </div>





                                                                <div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_phue9" value="PHUe9" name="categories[]">
                                  <label class="form-check-label" for="category_ phue9">PHUe9</label>

                                </div>




                                                                <div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_phue9" value="PHUe9" name="categories[]">
                                  <label class="form-check-label" for="category_ phue9">PHUe9</label>

                                </div>





                                                                <div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_j9jam" value="J9JAm" name="categories[]">
                                  <label class="form-check-label" for="category_ j9jam">J9JAm</label>

                                </div>




                                                                <div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_j9jam" value="J9JAm" name="categories[]" checked>
                                  <label class="form-check-label" for="category_ j9jam">J9JAm</label>

                                </div>





                                                                <div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_8obyw" value="8obyw" name="categories[]">
                                  <label class="form-check-label" for="category_ 8obyw">8obyw</label>

                                </div>




                                                                <div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_8obyw" value="8obyw" name="categories[]">
                                  <label class="form-check-label" for="category_ 8obyw">8obyw</label>

                                </div>

As you can see there are double checkboxes, which ofcourse I dont want

My blade file

@foreach($categories as $cat)
                                @if(count($entry->categories) > 0)
                                    @foreach($entry->categories as $catInEntry)

                                @if($catInEntry->slug == $cat->slug)
                                <div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_" value="" name="categories[]" checked>
                                  <label class="form-check-label" for="category_ "></label>

                                </div>
                                @else
                                <div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_" value="" name="categories[]">
                                  <label class="form-check-label" for="category_ "></label>

                                </div>
                                @endif
                                @endforeach 
                                @else
                                <div class="form-check form-check-inline">

                                  <input class="form-check-input" type="checkbox" id="category_" value="" name="categories[]">
                                  <label class="form-check-label" for="category_ "></label>

                                </div>
                                @endif
                            @endforeach

I had to add a third input checking an if because when there were no categories correlated there was no output, so I kinda fixed it this way

The Controller

public function edit($hash) {
        $entry = Entry::where('hash', $hash)->first();
        $categories = Category::all();
        $tagsInEntry = $entry->tags()->pluck('name');
        $implodedTags = implode('.', $tagsInEntry->toArray());
        $checked = '';
        return view('auth.entries-edit', compact('entry', 'categories', 'tagsInEntry', 'implodedTags', 'checked'));
        //return dd($entry->categories);
    }

I've tried some workarounds but all failed, any suggestion?




binding SplitContainerPanel with Checkbox checked

On a Basic SplitContainerPanel which has a Vertical Layout and two Panels, Panel1 and Panel2

Panel1 holds a Checkbox - Expand/Collapse

Can this be bound to the Panel2collapsed Property of the SplitContainer panel, so the panel2 is expanded only when checkbox is checked.




Checkbox Auto checked by database Value in code-igniter

In Database table I have some id. I want to show those id as checked in view page in checkbox automaticall.




Why is this CheckBox not checked?

I have an MVC ASP.Net Core website I'm writing and I've got a checkbox. I've spent hours thinking my binding was somehow wrong because I can save the value and it goes into the database but the view to the user always shows an unchecked checkbox. I finally had a look at the rendered HTML in Chrome Dev tools and this the checkbox:

    <input data-val="true" data-val-required="The Show Profile Picture field is required." id="ShowProfilePic" name="ShowProfilePic" type="checkbox" value="true">

The value is true like it is in the database but in the browser the check box is unticked. The value it's looking at in the Model and ViewModel are both bool. Any ideas?




vendredi 26 janvier 2018

Accept Terms and Conditions Once When Logging In

I have currently added a checkbox to my login page in order for the user to agree to the terms and conditions of our software. I added the required attribute to the checkbox so that the user would not be able to log in without checking it first. The part I'm having trouble with is making it so that the user only has to check the box once instead of checking it every time they log in. I read something about setting a cookie, but I couldn't figure out how to make that work.

What's the best way to go about this?




React - creating checkboxes based on data from object

I have a problem with implementing one of my ideas. Basically I want to create (in React) small app that:

1) Takes data from object, for example:

const obj = {
    person1: {
        name: 'Jessica',
        age: 25
    },
    person2: {
        name: 'Kate',
        age: 27
    },
    person3: {
        name: 'Lisa',
        age: 29
    }
};

But count of the attributes can be different than 3 (solution should be flexible).

2) Creates checkboxes with labels (names from the obj).

3) Has 2 buttons: one to check all of the checkboxes and second to deselect them.

4) Shows age when one (or more) of the users are selected, hides when not.

Seems like a simple thing to do, but I can't do it. First problem that I've encountered is how to iterate through object when creating checkboxes. forEach or map don't work. Any tips will be appreciated! Thanks in advance!




How to handle huge number of checkboxes in javafx (fxml)

I'm trying to develop a fxml window where are huge number of check boxes. I know i can handle those check boxes by fx:id for each check boxes separately. Is there any way to handle those check boxes easily? Here is a snapshot of my fxml window created using Gluon Scene Builder

FXML Scene containing multiple checkboxes




checkbox in list using rails will_paginate

I have the list that includes checkbox in each row. All the process are fine in one page. When the records exceeds one page and need to check the record on page 2 or 3, lost the checked value of the previous page. How can I solve this problem. Give me some great ideas.




Saving multiple checkbox into one column

I tried different ways to save multiple checkbox into database. I am so close right now but just last checkbox value are saving into database. I want them all and i couldn't make it. Here is my html codes.

<div class="col-xl-12">                     
<label>1st</label>
<input type="checkbox" name="data[]" value="00101"/>
<label>2nd</label>
<input type="checkbox" name="data[]" value="00102"/>
<label>3rd</label>
<input type="checkbox" name="data[]" value="00103"/>
<label>4th</label>
<input type="checkbox" name="data[]" value="00104"/>
</div>

In my controller.

  public function store(Request $request)
{

    $this->validate($request, array(
        'staff' => 'nullable',
        'dmc' => 'nullable',
        'workdone' => 'nullable',
        'product_id' => 'nullable'
    ));

    $ltjob = new Ltjob;
    $ltjob->staff = $request->staff;
    $ltjob->dmc = $request->dmc;
    $ltjob->product_id = $request->product_id;
    foreach ($request->input("data") as $data){
    $ltjob->workdone= $data;
}
    $ltjob->save();
    return redirect()->route('ltjobs.create');
}

Still saving last checkbox. When i try the dd($request->input("data")); before the foreach it gives me this:

  array:3 [▼
  0 => "00101"
  1 => "00102"
  2 => "00104"
]

And saving 00104. I hope you guys find the solution. And so sorry for my bad english. Thanks in advance.




jeudi 25 janvier 2018

How do I entirely remove the label from a CheckBox?

I want my JavaFX CheckBox to have no label.

Context: it's in the header of a TableColumn and it's (empahsis:) off-center.

I tried removing the label's text, but there's still some space on the right:

CheckBox with space

Next I tried changing the Content Display, but that didn't work either.

How do I get a CheckBox without a label or an extra space?




Multiple Dynamicaly created checkbox is not firing checked event in asp.net

private void BindGrantedPermissions() { try { string[] AppCodeArray; string[] ModuleCodeArray; DataSet dt = new DataSet(); clsAdmin objAdmin = new clsAdmin(); objAdmin.usertype = Convert.ToString(Session["PUserTypeCode"]); dt = objAdmin.BindPrmissionns(); if (dt.Tables.Count > 0) { if (dt.Tables[0].Rows.Count > 0) { tblPrmsn.Visible = true; AppCodeArray = Convert.ToString(dt.Tables[0].Rows[0]["Apps"]).Split(','); ModuleCodeArray = Convert.ToString(dt.Tables[0].Rows[0]["Modules"]).Split(','); for (int i = 0; i < AppCodeArray.Length; i++) { DataSet dtNew = new DataSet(); clsAdmin objAdminApp = new clsAdmin(); objAdminApp.ApplicationCode = AppCodeArray[i]; dtNew = objAdminApp.BindPrmissionns(); CheckBox chkApp = new CheckBox(); chkApp.ID = "ChkApp_" + i; chkApp.Checked = true; chkApp.AutoPostBack = true; chkApp.CheckedChanged +=CheckChanged; chkApp.Text = " " + dtNew.Tables[0].Rows[0]["AppName"].ToString(); HtmlTableRow trTbl = new HtmlTableRow(); HtmlTableCell tcAppChk = new HtmlTableCell(); tcAppChk.Controls.Clear(); tcAppChk.Controls.Add(chkApp); HtmlTableCell tcModule = new HtmlTableCell(); for (int k = 0; k < ModuleCodeArray.Length; k++) { for (int j = 0; j < dtNew.Tables[1].Rows.Count; j++) { if (ModuleCodeArray[k].ToString() == dtNew.Tables[1].Rows[j]["ModuleCode"].ToString()) { HtmlTable tblModule = new HtmlTable(); HtmlTableRow trModule = new HtmlTableRow(); HtmlTableCell tcModulecell = new HtmlTableCell(); CheckBox chkModule = new CheckBox(); chkModule.ID = "ChkModule_" + j; chkModule.Checked = true; chkModule.Text = " " + dtNew.Tables[1].Rows[j]["ModuleName"].ToString(); tcModulecell.Controls.Add(chkModule); trModule.Cells.Add(tcModulecell); tblModule.Rows.Add(trModule); tcModule.Controls.Add(tblModule); } } } trTbl.Cells.Add(tcAppChk); trTbl.Cells.Add(tcModule); tblPrmsn.Rows.Add(trTbl); } } else { tblPrmsn.Visible = false; } } else { tblPrmsn.Visible = false; } } catch (Exception ex) { clsLogger.ExceptionError = ex.Message; clsLogger.ExceptionPage = "admin/pi/UserPermissions/EditPermissions"; clsLogger.ExceptionMsg = "BindGrantedPermissions"; clsLogger.SaveException(); } }