lundi 30 avril 2018

How can I retrieve the check box state in python?

I am still new to python, I am trying to create an inventory management program for my work. I am stuck in the part where the user has to return some items back to stock after it was sent but returned by the customer. Basically I generate a list with the order name and beside each label there is a check box. The user has to tick the box beside the item that was returned. The problem is I cannot seem to retrieve the values of each box.

This is my code:

 def send(var,d):
    x=[]
    for i in range(0,len(var)):
        x.append(var[i].get())
    print(x)

def create_list(d,p,s,q,w):

    import tkinter as tk
    master4 = tk.Tk()
    var={}
    var2=[]
    tk.Label(master4, text='Description').grid(row=0,column=0)
    tk.Label(master4, text='Part number').grid(row=0,column=1)
    tk.Label(master4, text='Serial number').grid(row=0,column=2)
    tk.Label(master4, text='Well').grid(row=0,column=3)
    for i in range(0,len(p)):
        tk.Label(master4, text=str(d[i])).grid(row=i+1,column=0)
        tk.Label(master4, text=str(p[i])).grid(row=i+1,column=1)
        tk.Label(master4, text=str(s[i])).grid(row=i+1,column=2)
        tk.Label(master4, text=w).grid(row=i+1,column=3)
        var[i]=tk.IntVar()
        tk.Checkbutton(master4, text="", variable=var[i]).grid(row=i+1,

                                                                   column=4)
    tk.Button(master4, text='Next',
              command=lambda:returns.send(var,0)).grid(row=i+2,column=2)

It is part of a class called returns. The result is always a list of zeroes no matter which boxes I tick. The curious thing is that I wrote this exact code in a separate stand alone module and it worked like a charm.

Here's the one that worked:

    def sends(v):
        x=[]
        for i in range(0,len(v)):
        x.append(v[i].get())
        print(x)

   import tkinter as tk
   master = tk.Tk()
   var={}
   tk.Label(master, text='Description').grid(row=0,column=0)
   tk.Label(master, text='Part number').grid(row=0,column=1)
   tk.Label(master, text='Serial number').grid(row=0,column=2)
   tk.Label(master, text='Well').grid(row=0,column=3)
   for i in range(0,3):
       tk.Label(master, text='Ali').grid(row=i+1,column=0)
       tk.Label(master, text='Ali').grid(row=i+1,column=1)
       tk.Label(master, text='ALI').grid(row=i+1,column=2)
       tk.Label(master, text='Well').grid(row=i+1,column=3)
       var[i]=tk.IntVar()
       tk.Checkbutton(master, text="", variable=var[i]).grid(row=i+1,
                                                            column=4)
       tk.Button(master, text='Next',
                           command=lambda:sends(var)).grid(row=i+2,column=2) 
       tk.Button(master, text='Cancel', 
                              command=master.destroy).grid(row=i+2,
                                                                column=1)
       master.mainloop()

Why is one working the the other not? Does it have to do with the fact that the first one is part of a class and not just a function? I would appreciate any help.




JQuery (3.3.1) checkbox combination fails to return expected value

Having a little trouble with JQuery (version 3.3.1) checkbox implementation. See code sample below.

The problem

Selecting every combination works flawlessly except one, and I can't seem to pinpoint flaws in the code. The console doesn't complain when selecting the nonworking combination either. Nonworking combination:

[✓] Check Box 1
[   ] Check Box 2
[✓] Check Box 3
[✓] Check Box 4

Things to keep in mind:

  • Same checkbox combo fails there.
  • Every other combo works perfectly and returns expected results
  • I'm working locally with the downloaded, uncompressed jquery-3.3.1.js. Because the source refers to JQuery 2.1.3, I also downloaded the uncompressed jquery-2.1.3.js file. Same checkbox combo fails when referring to either JQuery version.
  • Code from source was not changed at all on my local machine.

Seems there's some flaw in the actual source code but can't seem to pinpoint any syntax errors or anything esle missing.

 $("#doIt").on("click", function () {
     var check = $('input:checked:checkbox[name=cc]');
     var id = '';
     $.each($(check), function (index) {
         id += $(this).attr('id');
     });
     if ($(check).is(':checked')) {
         switch (id) {
             case 'c1':
                 console.log(id);
                 break;
             case 'c2':
                 console.log(id);
                 break;
             case 'c3':
                 console.log(id);
                 break;
             case 'c4':
                 console.log(id);
                 break;
             case 'c1c2':
                 console.log(id);
                 break;
             case 'c1c3':
                 console.log(id);
                 break;
             case 'c1c4':
                 console.log(id);
                 break;
             case 'c2c3':
                 console.log(id);
                 break;
             case 'c2c4':
                 console.log(id);
                 break;
             case 'c3c4':
                 console.log(id);
                 break;
             case 'c1c2c3':
                 console.log(id);
                 break;
             case 'c1c2c4':
                 console.log(id);
                 break;
             case 'c2c3c4':
                 console.log(id);
                 break;
             case 'c1c2c3c4':
                 console.log(id);
                 break;
         }
     } else {
         alert('Un Checked');
     }
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="c1" name="cc" />
<label for="c1"><span></span>Check Box 1</label>
<br />
<input type="checkbox" id="c2" name="cc" />
<label for="c2"><span></span>Check Box 2</label>
<br />
<input type="checkbox" id="c3" name="cc" />
<label for="c3"><span></span>Check Box 3</label>
<br />
<input type="checkbox" id="c4" name="cc" />
<label for="c4"><span></span>Check Box 4</label>
<br />
<button id="doIt" type="button">Click Me!</button>



editing single or all selected users in a table with checkboxes - AngularJS

I'm loading a json into a table. I want my 'edit' button to edit a single row and my 'edit selected' to edit only those rows which are checked, but I can't figure it out. I only managed to get it to edit all rows at once.

example.json: https://pastebin.com/d8zDrxe5

index.htm: https://pastebin.com/acKyM0aG




Indexes or tags? For multiple checkboxes as buttons in IBOutletCollection - Swift 4 IOS

I'm kind of new to swift, but someone mentioned that I should use indexes or tags for the buttons in an IBOutletCollection.

Im not sure how to index or tag specific buttons, and then reference them in the cases:

// images of checked and unchecked boxes for the button to switch between
var BoxON = UIImage(named: "CheckBox")
var BoxOFF = UIImage(named:"UnCheckBox")

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    boxes.forEach {
        $0.setImage(BoxOFF, for: .normal)
        $0.setImage(BoxON, for: .selected)
    }

}

@IBOutlet var boxes : [UIButton]!

@IBAction func boxTouched(_ sender: UIButton) {
    sender.isSelected = !sender.isSelected
    let index = boxes.index(of: sender)!
    switch index {

        case 0:
            sender.isSelected = !sender.isSelected
        case 1:
            sender.isSelected = !sender.isSelected
        case 2:
            sender.isSelected = !sender.isSelected
        case 3:
            sender.isSelected = !sender.isSelected
        case 4:
            sender.isSelected = !sender.isSelected
        default:
            sender.isSelected = !sender.isSelected

    }
}

Thanks in advance! :)




how do i set programmatically checkbox property 'checked' or 'defaultChecked' in react

i am developing web application with react.

I want to dynamically set 'checked' property on checkbox.

It showed a proper screen that i wanted, but not working when i programmatically set 'checked' property.

So, i have searched about this.

some people recommended to use 'defaultChecked' property.

ant then i tried this. but failed.

It has not changed when i had given event that programmatically set checked property. It always showed defaultChecked value.

source code

render() {
list = {
 resource: {[...], [...] },
 ...
}
return (
<ParameterContainer values={ list } />
);
}

    class ParameterContainer extends React.Component {
    constructor(props) {
        super(props);

    }
    render() {
        const { values } = this.props;
        return (
            <div className="parameter-table">
                <div className="parameter-row-container">
                    <ul className="parameter-row title">
                        <li className="parameter parameter-1">valid</li>
                        <li className="parameter parameter-2">Key</li>
                        <li className="parameter parameter-3">Type</li>
                        <li className="parameter parameter-4">oid</li>
                        <li className="parameter parameter-5">rid</li>
                        <li className="parameter parameter-6">desc</li>
                    </ul>
                    {
                        values.resource.map((value, i) => {//one row
                            return (
                                <ParameterItem value={ value } index={ i } key={ i }/>
                            );
                        })
                    }
                </div>
            </div>
        );
    }
}

class ParameterItem extends React.Component {
    constructor(props) {
        super(props);

    }

    render() {
        const { value, index } = this.props;
        const items = [];

        for (let o in value) {
            if (o === "valid") {
                continue;
            }
            items.push(value[o]);
        }
        return (
            <ul className={`parameter-row parameter-row-${ index+1 }`}>
                <li className="parameter parameter-1">
                    <input type="checkbox" defaultValue={ value.valid } checked={ value.valid } onChange={ this.toggle }/> //i tried to this.
                    <Checkbox isChecked={ value.valid } /> // and then tried this...
                </li>
            </ul>
        );
    }

    toggle(e) {
        $(e.target).prop("checked", e.target.checked ? 0 : 1);
    }
}

class Checkbox extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            checked: !!this.props.isChecked
        };
    }

    handleChange = (e) => {
        const { target: { checked }} = e;
        this.setState({ checked });
    }

    render() {
        return (
            <input type="checkbox" checked={ this.state.checked } onChange={ this.handleChange } />
        );
    }
}




setValueAt for check box value in JTable Multiarray

I am currently having an issue with setting values to Checkbox in JTable. I need to store Boolean values per checkbox in rows of the table. I can display default(false) checkbox, but once I click check box, I get an exception; java.lang.ArrayIndexOutOfBoundsException: 0. I am not too familiar with multi arrays with Boolean and I cannot seem to figure out which part of my code is incorrect.

public static final int CHECKBOX= 0;
private final List<Data> datas;
private static boolean CHECKBOX_RENDERED[][] = new boolean[][]{};
private static Arrays array = null;

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    if (rowIndex >= this.datas.size()) {
        return null;
    }

    Data theData= this.datas.get(rowIndex);
    if (theData== null) {
        return null;
    }

    //Initialize the boolean field with table dimension
    CHECKBOX_RENDERED = new boolean[datas.size()][columnIndex];

    switch(columnIndex) {
    case CHECKBOX:
        array.fill(CHECKBOX_RENDERED[rowIndex], false);
        return false; //default
    default:
        throw new IllegalArgumentException("Invalid column index");
    }
}


@Override
public void setValueAt(Object value, int row, int column) {
    if (column == CHECKBOX) {
        Data data= this.datas.get(row);
        if (data!= null && value instanceof Boolean) {

            if (CHECKBOX_RENDERED[row][column]) {
                CHECKBOX_RENDERED[row][column] = false;
          //I think I need to set Boolean value to the specific array field 
          //but how.? 
            } else {
                CHECKBOX_RENDERED[row][column] = true;
            }

            fireTableCellUpdated(row, column);
        }
    }
}




Deleting Selected Input is not working perfectly, cannot figure it out

Hope this isn't too basic for StackOverflow, but other sites forums don't seem advanced enough to answer my questions which are a little over basic.

I'm trying to delete multiple selections, by adding the checkboxes on each listing and having one button for the entire form.

My test website is already hosted so you can view the real deal here: https://ift.tt/2jjsZPk

Please log in with "admin" (no password) and then you'll get to the cash-listing page. These are the listings I would like to delete, and as you can see, the checkboxes are there, but the button only works for one checkbox.

I done the research, and I tried to compare my code, and the code involved does match up. But my code is a little complex for me to find out exactly what I'm doing wrong. I'm new to PHP (started learning it 3 weeks ago!) so this might seem really basic to you guys. Please bare with me though, as you can see the rest of the website is my own work (proudly done with barely 3 weeks php and mysql knowledge!), I'm trying my best not to ask questions but this has got me really stuck. All the other buttons (delete, delete all, edit, add new, etc) are working very nicely. Only the delete-selected models is getting me stuck...

I'm not sure if you still need me to post the code snippets if I gave you the website link already, but if I do please let me know.

P.S. I already received downvotes for this question. Is it really such a crime to post a basic question on Stackoverflow?




How can i get data from data source and display in list view and select multiple items using checkbox and display the selected items in next screen

In REACT NATIVE How can i display data in list view and select multiple items using checkbox and display the selected items in next screen can any one give me example




A checkbox should get checked on clicking a button

I need a small help.

Can someone help in an excel VB Macro for the below case:

I want to check a checkbox on clicking of a button.

"So everytime i click a button the linked checkebox should get checked automatically"




dimanche 29 avril 2018

How do I setup a list of checkboxes in Qt Designer?

In my window, I have one menu which is a set selections, one of which can be current. For example, in my Browser I have sub-menus where I can select the Zoom Factor.

For example, it could be offering three options like these:

  50%
√ 100%
  150%

Whenever the user selects one of the 50%, 100%, or 150%, the current selection needs to get unselected. I was hoping we could set that up in designer so it becomes automatic when I create the window. (i.e. the designer generated code would be smart enough to add those 3 items in a QActionGroup.)

I've seen code that can be used to generate such a menu using QRadioButton, but I don't see a way to replicate that behavior in designer. Is that not available in the tool?




checkbox could not uncheck php

I have written a code to save the check values of checkboxes to database.

check condition is working fine as in the checked values are saving to database when submit and it keeps checked when submit and refresh.

But when it uncheck and submit then refresh the page the checkbox still keeps remained checked. It won't saved the status of unchecked.

I include a chunk code which is related to this issue. If anyone can get the issue that'd be great.

   $sql_stamp = "SELECT check_list FROM time_stamps WHERE nJobNumber=".$nJobNumber;
                $query_stamp = $conn->prepare($sql_stamp);
                $query_stamp->execute();
                $numRows = $query_stamp->rowCount(); 
                if($numRows > 0){
                    $row_stamp = $query_stamp->fetch(PDO::FETCH_ASSOC);
                    $checkboxes = explode(',',$row_stamp['check_list']);
                    echo ' <td><center> <input type="checkbox" name="check_list[]" value="shop_drawing" '.(in_array( "shop_drawing",$checkboxes) ? "checked=checked" : "").'></td>';
                    echo ' <td><center><input type="checkbox" name="check_list[]" value="site_measure" '.(in_array( "site_measure",$checkboxes) ? "checked=checked" : "").'></td>';
                    echo ' <td><center><input type="checkbox" name="check_list[]" value="shop_drawings_approved" '.(in_array( "shop_drawings_approved",$checkboxes) ? "checked =checked" : "").'></td>';
                    echo '<td><center> <input type="checkbox" name="check_list[]" id="check" value="batch" '.(in_array( "batch",$checkboxes) ? "checked=checked" : "").'></td>';
                    echo '<td><center> <input type="text" name="batch_no"><br>  </td>';
                    echo ' <td><center> <input type="submit" name="submit" value="Submit"/> </td>';
                    echo '<td><input type="hidden" name="job_number[result]" value="'."true".'"</td>'; 
                    echo '<td><input type="hidden" name="job_number[number]" value="'.$nJobNumber.'"</td>';
                }else{
                    echo '<td><center><input type="checkbox" name="check_list[]" id="check" value="shop_drawing"></td>';
                    echo '<td><center><input type="checkbox" name="check_list[]" id="check" value="site_measure"></td>';
                    echo '<td><center><input type="checkbox" name="check_list[]" id="check" value="shop_drawings_approved"> </td>';
                    echo '<td><center> <input type="checkbox" name="check_list[]" id="check" value="batch"></td>';
                    echo '<td><center> <input type="text" name="batch_no"><br>  </td>';
                    echo "<td><center> <input type='submit' name='submit' value='submit'></td>";
                    echo '<td><input type="hidden" name="job_number[result]" value="'."false".'"</td>'; 
                    echo '<td><input type="hidden" name="job_number[number]" value="'.$nJobNumber.'"</td>'; 
                }


                echo "</tr> </form>";
            }
        echo "</tbody> </table>";

      ?>

Insert values to database:

if(isset($_POST['submit']))
{
    $checkbox = $_POST["check_list"];
    $job_number = $_POST["job_number"];
    $batch_no = $_POST["batch_no"];
    date_default_timezone_set('Australia');
    $date_time = date("Y-m-d h:i:sa");
    //$username = "$SESSION[userid]";
    if($job_number["result"] == "true"){
        if(!empty($_POST['check_list'])) {
            $checkboxes = implode(",",$_POST['check_list']);
            $stmt = $link->prepare('UPDATE time_stamps SET time_date=?,username=?, batch_no=?,check_list=? WHERE nJobNumber=?');
            $stmt->bind_param('ssssi',$date_time,$username,$batch_no,$checkboxes,$job_number["number"]);
            $stmt->execute();
        }
    }else{
        if(!empty($_POST['check_list'])) {
            $checkboxes = implode(",",$_POST['check_list']);
            $stmt = $link->prepare('INSERT INTO time_stamps (nJobNumber,time_date,username,batch_no,check_list) VALUES (?,?,?,?,?)');
            $stmt->bind_param('issss',$job_number["number"],$date_time,$username,$batch_no,$checkboxes);
            $stmt->execute();
        }
    }

}




Set values from array to true in Ionic2 app check-boxes pop-up menu list

In pop-up menu with check-boxes:

     this.itm = [
          { name: 'name1', checked: false },
          { name: 'name2', checked: false },
          { name: 'name3', checked: false },
          { name: 'name4', checked: false },
          { name: 'name5', checked: false },     
          { name: 'name6', checked: false },     
          { name: 'name7', checked: false },     
        ];
      }

if I have some updated array: private arr: any[] = []; with particular content, retrieved from database record with back-end echo for example, what is a proper way to set this values in check-boxes pop-up menu to true as by default, to see this names already checked with opening:

   name3
   name5
   name7




Insert 2 selected checkbox into 2 textfield

I have multiple checkbox that can be selected by user, however i cant find out a way how to distinguish each values into 2 different textfield

As you can see i have multiple choice of checkbox, but user can only check 2 checkbox because it will set the timestamp range.

enter image description here

But, i end up with this code, and it does not work as i wanted as it displays the same thing in both texfield

 $('input[type="checkbox"]').on('click', function() {
   var is_checked = $(this).prop('checked');
   var val = '';
   if (is_checked) val = this.value;
   $('input[text="input"]').val(val);
 });

And it displays like this:

enter image description here




ListView with Checkboxes: How can I check if it's checked or not?

In my programm I have a simple ListView and set an ArrayAdapter on it:

arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), 
R.layout.row_layout_checkbox, R.id.textView_checkbox, list);
listView.setAdapter(arrayAdapter);

"list" is a String-Array(String[]).

Layout XML row_layout_checkbox :

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

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginRight="14dp"
    android:layout_marginEnd="14dp"/>

<TextView
    android:id="@+id/textView_checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_centerVertical="true"
    android:layout_marginLeft="17dp"
    android:layout_marginStart="17dp"
    android:text="TextView"
    android:textColor="@color/colorBlack"/>
</RelativeLayout>

So my question: How can I check which checkboxes are checked or not so I can put true or false in an boolean-Array?

(It should can check the checkboxes of each item and should be multiple choice not single choice.)




add dynamic checkbox in java windowbuilder

I want to add a dynamic checkbox after selecting an item in combo box. I am working on eclipse and design my frame on window builder.

    final JComboBox<String> comboBox = new JComboBox<String>();
    comboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String typeName = comboBox.getSelectedItem().toString();
            for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
                JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
                c.setVisible(true);
                coursePanel.add(c);

                frame.repaint();
                frame.validate();

                System.out.println(c.getText());
            }
        }
    });
    comboBox.setBounds(208, 221, 91, 20);
    frame.getContentPane().add(comboBox);

Why the frame does'nt show the checkbox? Thank you.




samedi 28 avril 2018

JSP checkbox returning only one, first value

Im learning about Jsp and servlets. In my jsp im am returning a table of employees, im trying to delete multiple rows from checkbox by userId. When i run servlet i got filled table with employees but by checkbox i can only delete first employee (first row), every other is returning null...

<div class ="removeBtn"> <!-- remove button for multiple delete -->
     <input type="submit" value="Remove selected" form="multipleDeleteRowsId">
</div>

       <table class="employeeInfoTable" >
        <tr>
            <th></th>
            <th>First Name</th>
            <th>Second Name</th>
            <th>Last Name</th>
            <th>Date of Join</th>
            <th>Branch</th>
            <th>Action</th>
        </tr>

        <c:forEach var="tempUser" items="${employeesList}">

            <c:url var="idLink" value="EmployeeControllerServlet">
                <c:param name="command" value="LOAD"/>
                <c:param name="employeeID" value="${tempUser.id}"/>
            </c:url>
            <c:url var="removeLink" value="EmployeeControllerServlet">
                <c:param name="command" value="DELETE"/>
                <c:param name="deleteByID" value="${tempUser.id}"/>
            </c:url>

            <tr>
                <td>
                    <form action="EmployeeControllerServlet" method="get" id="multipleDeleteRowsId" > <!-- here is multiple delete -->
                        <input type="hidden" name="command" value="DELETE">
                        <input type="checkbox" name="selectedRow" value="${tempUser.id}">${tempUser.id}
                    </form>
                </td>
                <td>${tempUser.firstName}
                </td>
                <td>${tempUser.surname}
                </td>
                <td>${tempUser.lastName}
                </td>
                <td>${tempUser.dateOfJoin}
                </td>
                <td>${tempUser.branch}
                </td>
                <td>
                    <ul id="menu">
                        <li><a href="#">Edit</a>
                            <ul>
                                <li><a href="#"><a href="${idLink}">More Info</a></a></li>
                                <li><a href="#"><a href="${removeLink}"
                                                   onclick="return confirm( 'Are you sure you want to delete?')">Remove</a></a>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </td>
            </tr>
        </c:forEach>
    </table>

here is servlet

    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {

        String[] selected = request.getParameterValues("selectedRow");
        for(int i = 0; i<selected.length; i++){
            System.out.println(" " + selected[i] + " ");
        }
    } catch (Exception e) {
        System.out.println("not deleted ? " + e.getCause());
    }
}

finally result for other rows than first is null..

Thanks in advance




How can I save the selected values ​of a CheckBox from a user in FireBase?

How can I save the selected values ​of a CheckBox from a user with the FireBase uid and stored in SharedPreferences?

Here is my code.

public class ingredientesSemanales extends AppCompatActivity
{
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    DatabaseReference ingredientes;
    ArrayList<String> selectedItems = new ArrayList<>();
    String[] items;
    ListView ch1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ingredientes_semanales);
        ch1 = (ListView) findViewById(R.id.checkeable_list);
        ingredientes = ref.child("Ingredientes Semanales").child("Lunes");

        ch1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        ch1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            SharedPreferences preferences=getSharedPreferences("ItemsSelectedFromUser", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String selectedItem = ((TextView)view).getText().toString();
                if(selectedItems.contains(selectedItem)){
                    selectedItems.remove(selectedItem);
                }else{
                    selectedItems.add(selectedItem);

                }

                editor.putString();
            }
        });
    }

    @Override
    protected void onStart()
    {
        super.onStart();

        ingredientes.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                String value = dataSnapshot.getValue(String.class);
                items = value.split(",");
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.semanarow, R.id.txt_lan, items);
                ch1.setAdapter(adapter);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
    }
}




How to Make Select All Check Box

I want when i click select all then all checkbox will selected and when I click again all checkbox will deselect.

but when I click it nothing happen.

my code

jsfiddle link

$(document).ready(function() {
  $("#check-all").click(function() {
    var check = $(this).attr('checked');
    if (check == "checked") {
      $("#deleteid").attr('checked', 'checked');
    } else
      $("#deleteid").removeAttr('checked');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sort_select_delete_form" method="get">

  <div class="btn-group">
    <a href="#check-all" class="btn btn-primary" id="check-all">Select All</a>
    <input type="submit" class="btn btn-danger" value="Delete Selected">
  </div>

  <input class="form-check-input" type="checkbox" value="1000000001" id="deleteid[]" name="deleteid[]">select1
  <input class="form-check-input" type="checkbox" value="1000000002" id="deleteid[]" name="deleteid[]">select2
  <input class="form-check-input" type="checkbox" value="1000000003" id="deleteid[]" name="deleteid[]">select3
  <input class="form-check-input" type="checkbox" value="1000000004" id="deleteid[]" name="deleteid[]">select4
  <input class="form-check-input" type="checkbox" value="1000000005" id="deleteid[]" name="deleteid[]">select5

</form>



Changing font colors of rows and columns with checkboxes

I am looking for a way to change the font colors of the row and column contents of a table with the assigned checkbox at the top and on the left side of the table. so when a checkbox is clicked either a corresponding row or column contents change font color. I don't need multiple colors. I just need to change font color to an assigned color only. Multiple row checkbox and column checkboxes may be clicked together, this shouldn't cause a complication. Thank you for your help!

 <style type="text/css">
    .tb {
        font-size: 12px;
        border: 1px solid #CCC;
        font-family: Arial, Helvetica, sans-serif;
    }

    .tb td {
        padding: 4px;
        margin: 3px;
        border: 1px solid #CCC;
    }
</style>

<table class="tb">
    <tbody>
        <tr>
            <td></td>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Number</td>
            <td>Number</td>
            <td>Text</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Number</td>
            <td>Number</td>
            <td>Text</td>
            <td>Text</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Text</td>
            <td>Number</td>
            <td>Number</td>
            <td>Text</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Text</td>
            <td>Number</td>
            <td>Text</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
        </tr>
        <tr>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check" /> Switch</label>
            </td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
            <td>Number</td>
        </tr>
    </tbody>
</table>




vendredi 27 avril 2018

React checkbox doesn't update on render correctly when clicked

I have the following code to display a list of options in dropdown

_.map(listOptions, (value) => {
           const { key, label, checked } = value;    
            return (
               <li key={key} onClick={(e) => this.onSelect(e, key, checked)}>
                   <input type="checkbox" checked={!!checked} onChange={(e) => this.onSelect(e, key, checked)}/>
                   {label}
               </li>
            );
})

When I click on a list item (outside the checkbox), the function call is made correctly which sets the state and the list options look good.

When I click on the actual checkbox, the checkbox is not enabled. It still remains in its previous state. When I click another checkbox, the previous one I clicked gets enabled. The options are always one step back to the current state.

This only happens when I click on a checkbox. The options work correctly when I click on the list item. I tried multiple things for input checkbox onChange like e.preventDefault() and e.stopPropagation, however it still doesn't work.




Android: saving checkbox-state of ListView items into instances of custom object

My ultimate goal is to store an instance of the custom object "Place" for each item of the ListView in an SQLite table.

step 1 would be simply extracting the Place objects and I was able to get the various member variables of Place using an adapter but I have been trying for days to get the checked-state of each checkbox within the listview but cannot get it to work and it shouldn't be that difficult. I have tried every listener I can think of but it is not registering when I check a box. Finally, I do need the checked-state as an integer (1 or 0) rather than a boolean so I can save it to the database. Below I have posted the code for a tester app version I have been working on so I stop screwing up the real thing and I really would appreciate any help!

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:gravity="center_vertical"
    android:onClick="itemClicked"
    android:paddingRight="8dp"/>

<TextView
    android:id="@+id/place_nameandaddress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:gravity="center_vertical"
    android:minHeight="?android:listPreferredItemHeight"/>

</LinearLayout>


public class Place {

String mName;
String mAddress;
double mLatitude;
double mLongitude;
public int mCheckedStatus;

public Place(String name, String address, double latitude, double longitude, int integer){
    mName = name;
    mAddress = address;
    mLatitude = latitude;
    mLongitude = longitude;
    mCheckedStatus = integer;
}

public String getName() {
    return  mName;
}

public String getAddress() {
    return  mAddress;
}

public double getLatitude() {
    return  mLatitude;
}

public double getLongitude() {
    return  mLongitude;
}

public int getCheckedStatus(){ return mCheckedStatus;}

public void setCheckedStatus(int integer){
    mCheckedStatus = integer;
}

public boolean isSelected() {
    if (mCheckedStatus ==1) {
        return true;
    } else {
        return false;
    }
 }
}

public class PlaceAdapter extends ArrayAdapter<Place> {

public PlaceAdapter(@NonNull Context context, int resource, ArrayList<Place> places) {
    super(context, 0, places);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.place_item, parent, false);
    }

    Place currentPlace = getItem(position);

    TextView placeview = convertView.findViewById(R.id.place_nameandaddress);

// remove commas so can later use commas to separate items of the arraylist
    String name = currentPlace.getName().replace(",", "");
    String address = currentPlace.getAddress().replace(",", "");
    placeview.setText(name + " at " + address);


    double latitude = currentPlace.getLatitude();
    double longitude = currentPlace.getLongitude();
    Log.i("Debugging: Lat and Long", String.valueOf(longitude) + String.valueOf(latitude));

    CheckBox checkbox = convertView.findViewById(R.id.checkbox);
      if (currentPlace.isSelected()) {
          checkbox.setChecked(true);
      } else {
          checkbox.setChecked(false);
      }

        return convertView;

    }
}




public class MainActivity extends AppCompatActivity {

ListView listView;
Uri mIntentUri;
CheckBox checkBox;
int checkboxstatus;
Place currentplace;

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

    ArrayList<Place> places = new ArrayList<Place>();
    places.add(new Place("name1", "address1", 12.3, 23.3, 0));
    places.add(new Place("name2", "address2", 12.4, 23.4, 0));
    places.add(new Place("name3", "address3", 12.5, 23.5, 0));
    places.add(new Place("name4", "address4", 12.6, 23.6, 0));
    places.add(new Place("name5", "address5", 12.7, 23.7, 0));
    listView = findViewById(R.id.listview);
    PlaceAdapter placeAdapter = new PlaceAdapter(this, 0, places);
    listView.setAdapter(placeAdapter);
}

//get user input from editor and saves value entered into new or edited goal into database
    public void saveGoal() {

       PlaceAdapter allplacesAdapter = (PlaceAdapter) listView.getAdapter();

        ArrayList<String> places = new ArrayList<>();
        double latitude = 0;
        double longitude = 0;

        for ( int i=0; i < allplacesAdapter.getCount();i++) {
            currentplace = allplacesAdapter.getItem(i);
            String name = currentplace.getName().replace(",","");
            String address = currentplace.getAddress().replace(",","");

            View view =  LayoutInflater.from(this).inflate(R.layout.place_item, listView, false);
            checkBox = view.findViewById(R.id.checkbox);
            if (checkBox.isChecked()){
                currentplace.setCheckedStatus(1);
            }
                else {
                currentplace.setCheckedStatus(0);
            }

            checkboxstatus = currentplace.getCheckedStatus();                
            latitude = currentplace.getLatitude();
            longitude = currentplace.getLongitude();
            String placeString = name + "," + address + "," + latitude + "," + longitude + "," + checkboxstatus;
            Log.i("Debugging: placeString",placeString);
            places.add(placeString);
        }
        String arrayString = android.text.TextUtils.join(";", places);
        Log.i("Debugging: arrayString",arrayString);

        if (TextUtils.isEmpty(arrayString)) {
            return;
        }
        ContentValues contentValues = new ContentValues();
        contentValues.put(GoalContract.GoalEntry.COLUMN_PLACE, arrayString);
        Log.i("Debugging:contentValues", contentValues.toString());

        // informs user of whether values entered into the GoalEditor were saved or there was an error
        //if (mIntentUri == null) {
            Uri newUri = getContentResolver().insert(GoalContract.GoalEntry.FINAL_CONTENT_URI, contentValues);
            if (newUri == null) {
                Toast.makeText(this, "Error with saving goal", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Goal successfully saved", Toast.LENGTH_LONG).show();
            }
    }

// sets options menu if GoalEditor screen
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_goaleditor, menu);
    return true;
}

// determines what should happen if the different menu options in the GoalEditor screen are selected
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_save:
            saveGoal();
            finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
  }
}




mat-checkbox does not check if condition is false (only on double click)

I have an entity that has a variable that needs to be the oposite of the checkbox state.

enitity.enabled = true

The checkbox is there to "mark to delete" the item. If you mark and send the form, the item marked is soft deleted.

With this in mind, the checkbox is exactly like this:

<mat-checkbox [(ngModel)]="!entity.enabled"></mat-checkbox>

For some reason, the enitity.enabled value is only changed when the second click applies.

I looked a lot for a solution or if this is a bug, nothing found I came here for your help.

Any idea how to fix this issue?

Example here




How refresh button radio in list user (table)

when i clik button radio, the popup display detail user A correct, but when i click in radio of line 2 (userB), the popup display details of user A (also details userA and no detail for userB) !!, how correct this problem, refresh button radio ?




JS - Uncheck a checkbox and another checkbox will untick

I have two checkboxes in a form. onclick if a checkbox called email is unchecked how can I get the other checkbox to also uncheck (if it is checked)?

document.getElementById('email').onclick = function() {


     if (!this.checked) {
        !document.getElementById("other").checked;
    } else {
        // if not checked ...
    }
};

Am I completey barking up the wrong tree? Any help appriciated




checkbox click event fired twice for class name vs once for id (jquery)

I have the following piece of code running in a snippets plugin in wordpress.

Jquery:

<script>
    jQuery( document ).ready(function(event) {

        jQuery(".checkbox").click(function() {

                if(jQuery(this).is(":checked"))
                    alert('checked');

                else
                    alert('unchecked ');


        });

    });

</script>

HTML:

<div class="checkbox">
      <h2><label><input type="checkbox" class="checkbox" value="">Ignore Registration</label></h2>
</div>

When the checkbox is checked, i received two alerts (checked, followed by unchecked).

When the checkbox is unchecked, i received two alerts as well (unchecked, and unchecked).

I'm not sure why this is happening, but when i changed the input tag to use the id instead of class, the solution works perfectly.

jQuery("#checkbox").click ..........

<input type="checkbox" id="checkbox"..........

Am just trying to find out whats happening, or the difference in using classes and ids for the click event




jeudi 26 avril 2018

MS Excel Form Chebbox Change Font Size

From reading around, it appears that the font in Form checkboxes in Excel can't be modified, and to use ActiveX checkboxes instead.

However, I'm looking at a spreadsheet that someone else created (who has long since departed) where the Form checkbox definitely has its font modified. I'm not sure how they were able to accomplish this. Any ideas?

In the meantime, I've copied their form into my spreadsheet as a workaround. The default form checkbox just has too small of a font, that's all I need to modify.




Create multiple checkboxes from a list and get all values

I would like to generate multiple checkboxes from a large list, and get all the values.

Here is my code so far (the list could be much larger):

from Tkinter import *

def print_ingredients(*args):
   values = [('cheese',cheese.get()),('ham',ham.get()),('pickle',pickle.get()),('mustard',mustard.get()),('lettuce',lettuce.get())]
   print values

lst = ['cheese','ham','pickle','mustard','lettuce']

top = Tk()

mb=  Menubutton ( top, text="Ingredients", relief=RAISED )
mb.grid()
mb.menu  =  Menu ( mb, tearoff = 0 )
mb["menu"]  =  mb.menu

cheese=IntVar()
ham=IntVar()
pickle=IntVar()
mustard=IntVar()
lettuce=IntVar()

l = mb.menu.add_checkbutton(label="cheese", variable = cheese)
l = mb.menu.add_checkbutton(label="ham", variable = ham)
l = mb.menu.add_checkbutton(label="pickle", variable = pickle)
l = mb.menu.add_checkbutton(label="mustard", variable = mustard)
l = mb.menu.add_checkbutton(label="lettuce", variable = lettuce)

btn = Button(top, text="Print", command=print_ingredients)
btn.pack()

mb.pack()

top.mainloop()

This works as intended but when it is a much larger list it seems unnecessary to write all of this out.

Is there a way to create the checkboxes/checkbuttons (and then get their values) solely by iterating through the list of strings?




How to get the object of selected checkbox in Android

I'm making a shopping list App in android with firebase, I obtain the list of items , and show in array adapter well.When I need to check an item and change it in Firebase . I don't know if I have to do that in the array adapter or in my fragment. My class is itemCart and extends from another Food that have an ID. My problem is when I check the item, and i can't acces to the object that contains this checkbox, how can I do ?

I have this class:

public class itemCart extends Food implements Serializable {
    public String quantity;
    public String mesurementunit;
    public Boolean bought;


    public itemCart(){}

    public itemCart(Food food, String quantity, String mesurementunit, Boolean bought) {
        super(food.get_id());
        this.quantity = quantity;
        this.mesurementunit = mesurementunit;
        this.bought = bought;
    }

    public String getQuantity() {
        return quantity;
    }

    public void setQuantity(String quantity) {
        this.quantity = quantity;
    }

    public String getMesurementunit() {
        return mesurementunit;
    }

    public void setMesurementunit(String mesurementunit) {
        this.mesurementunit = mesurementunit;
    }

    public Boolean getBought() {
        return bought;
    }

    public void setBought(Boolean bought) {
        this.bought = bought;
    }
}

Also I have this ArrayAdapter

public class ShoppingListFragmentArrayAdapter extends ArrayAdapter<itemCart> {
    List<itemCart> listItemsCart;
    itemCart mitemCart;

    FirebaseDatabase mFirebaseDatabase;
    String uid;
    FirebaseAuth mFirebaseAuth;
    DatabaseReference mitemCardReference;


    public ShoppingListFragmentArrayAdapter(@NonNull Context context, int resource, List<itemCart> objects) {
        super(context, resource, objects);
        this.listItemsCart = objects;

    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView == null){
            convertView = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.row_shopping_cart,parent,false);
        }
        mFirebaseAuth = FirebaseAuth.getInstance();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        uid = mFirebaseAuth.getUid().toString();
        mitemCardReference = mFirebaseDatabase.getReference().child("carts").child(uid);


        TextView foodName = (TextView) convertView.findViewById(R.id.txtViewNameShoppingList);
        CircleImageView imgFood = (CircleImageView) convertView.findViewById(R.id.foodCardCircleView);
        CheckBox checkBoxFood = (CheckBox) convertView.findViewById(R.id.chartFoodChecklist);

        mitemCart = listItemsCart.get(position);
        checkBoxFood.setChecked(mitemCart.getBought());
        foodName.setText(mitemCart.getCorrectLanguageName()+" "+mitemCart.getQuantity()+" "+mitemCart.getMesurementunit());
        Glide.with(imgFood.getContext())
                .load(mitemCart.getImg_firebase())
                .into(imgFood);
        checkBoxFood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //here i wanna get the object
            }
        });

        return convertView;
    }
}

Is correct to do this in the Adapter or I have to do in my Fragment ?

public class ShoppingListFragment extends Fragment {

    private View rootView;

    private ShoppingListFragmentArrayAdapter mshoppingListFragmentArrayAdapter;
    private ProgressBar mProgressBar;
    private CheckBox mcheckBox;
    private Button mBtnClear;

    private String uid;

    List<itemCart> itemCarts;

    private itemCart mitemCart;

    private ListView mListView;

    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference mItemCartReference;

    public ShoppingListFragment (){

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        uid = FirebaseAuth.getInstance().getCurrentUser().getUid().toString();

        mFirebaseDatabase = FirebaseDatabase.getInstance();
        mItemCartReference = mFirebaseDatabase.getReference().child("carts").child(uid);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_shopping_card_list,container,false);

        mListView = (ListView) rootView.findViewById(R.id.lstViewShoppingCart);
        mProgressBar = (ProgressBar) rootView.findViewById(R.id.progressBarCartFoodList);
        mBtnClear = (Button) rootView.findViewById(R.id.btnClearShoppingList);
        mcheckBox = (CheckBox) rootView.findViewById(R.id.chartFoodChecklist);

        itemCarts = new ArrayList<>();

        mProgressBar.setVisibility(View.VISIBLE);

        mItemCartReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                clearItemCartList();
                for (DataSnapshot itemSnapshot : dataSnapshot.getChildren()) {
                    mitemCart = itemSnapshot.getValue(itemCart.class);
                   updateitemCartList(mitemCart);
                }
                mProgressBar.setVisibility(View.INVISIBLE);


                mshoppingListFragmentArrayAdapter = new ShoppingListFragmentArrayAdapter(getActivity(),R.layout.row_shopping_cart,itemCarts);
                mListView.setAdapter(mshoppingListFragmentArrayAdapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });



        return rootView;
    }



    private void updateitemCartList(itemCart item ) {
        itemCarts.add(item);
    }
    private void clearItemCartList(){
        itemCarts.clear();
    }

}

When my checkbox is clicked or changed I need to obtain the id of the object itemCart this.

In this code in the itemCart object of my arrayAdapter always recive the last one that I have.




hide and show rss feeds in android studio using checkboxes

Hello guys i am doing an application to show rss feed according to interest . i want to use checkboxes to hide and show rss feeds : This is my page for showing the rss feed . I have the following classes (Downloader , RSSParser , Connector , ErrorTracker). I want to show and hide on checkboxes . Kindly help me use this code to hide the rss i want to hide using checkbox from another class

public class Businesstimesrss extends AppCompatActivity {

final static String urlAddress2  = "http://wap.business-standard.com/rss/latest.rss";
final static NewFeedOriginator add1  = new NewFeedOriginator("Business Standard","http://wap.business-standard.com/rss/latest.rss");
final static NewFeedOriginator add2  = new NewFeedOriginator("Business Times","http://www.businesstimes.com.sg/rss/top-stories");
final static NewFeedOriginator add3  = new NewFeedOriginator("Fox Sports","https://api.foxsports.com/v1/rss?partnerKey=zBaFxRyGKCfxBagJG9b8pqLyndmvo7UU&tag=nfl");

ArrayList<Article> articles = new ArrayList<>();
boolean started =false;
boolean bdfinished = false;
boolean cdfinished = false;
boolean edfinished = false;
Downloader bd ,cd , ed;

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

    final ListView lv = (ListView) findViewById(R.id.lv);



    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);




    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!started){
                bd = new Downloader(Businesstimesrss.this,add1,lv);
                bd.execute();

                cd = new Downloader(Businesstimesrss.this,add2,lv);
                cd.execute();

                ed = new Downloader(Businesstimesrss.this,add3,lv);
                ed.execute();

                started = true;
                return;
            }
            if(bd.getStatus() == Downloader.Status.FINISHED && !bdfinished){
                articles.addAll(bd.getDownloadedArticles());
                bdfinished = true;
            }

            if(cd.getStatus() == Downloader.Status.FINISHED && !cdfinished){
                articles.addAll(cd.getDownloadedArticles());
                cdfinished = true;
            }
            if(ed.getStatus() == Downloader.Status.FINISHED && !edfinished){
                articles.addAll(ed.getDownloadedArticles());
                edfinished = true;
            }


            if(bdfinished && cdfinished && edfinished )
            lv.setAdapter(new CustomAdapter(Businesstimesrss.this , articles));

        }
    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.homepage, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == android.R.id.home) {
        startActivity(new Intent(Businesstimesrss.this,Businesslink.class));
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}




how to add a checkbox with condition in oracle apex

I have created one tabular form(legacy page) in oracle apex and in some columns i have given type checkbox.I just want to add a condition that if that column value is 'y' then it is already checked otherwise unchecked. please help me regarding this.




How do you enable / disable a button based on list of dynamically created checkboxes?

I've got a html table that is dynamically populated with data. If the user is in a certain role a checkbox will be visible to them on all rows in the table. If ANY of those checkboxes are ticked then a button on the bottom should become enabled.

Here's the checkbox:

<tr>
    <td *ngIf="role.IsValid">
        <input #myCheckbox type="checkbox" [(ngModel)] = "items.itemId" id="checkbox" [attr.checked]="items.itemId" (click)="updateItemCount(myCheckbox.checked)" />
    </td>
<tr>

Under the table I've got a button that should be disabled when no checkboxes have been selected and become enabled as soon as at least 1 checkbox has been clicked.

<button type="button" (click)="openModal()" [attr.disabled]="itemsSelectedCount === 0">Submit</button>

The typescript for the updateItemCount() method is below and simply increases or decreases the itemsSelectedCount variable by 1:

updateItemCount(checked: boolean) {
  if (checked) {
    ++this.itemsSelectedCount;
  }
  else {
    --this.itemsSelectedCount;
  }
}

I've debugged and can see the correct true or false value entering the updateItemCount method and the itemsSelectedCount variable changing, but the button stays disabled. How can I conditionally enable this once the itemsSelectedCount goes above 0?




Keep checkbox array checked after submit-not working

I have refereed and tried many solutions provided in this type of question threads before asking my question as none of them working properly for me. I have one mysql table of students which stores stud name, marks. I am retrieving that data from database using while loop.

$query="select * from student";
$rs=  mysql_query($query) or die(mysql_error());


<?php if(mysql_num_rows($rs)){ ?>
  <table border="5" cellspacing="5" width="50%" align="center">
      <tr>
          <th>No</th>
          <th>Name</th>
          <th>Marks</th>
          <th>Operation</th>
          <th>  <input type ="submit" name="delete" value="Delete"></th>
      </tr>
      <?php


 while($row=mysql_fetch_array($rs))
          {


?>
      <tr>
           <th><?php echo $row['rollno']; ?></th>
          <th><?php echo $row['name']; ?></th>
          <th><?php echo $row['marks']; ?></th>
                      <th><a href="AllOperation.php?&no=<?php echo $row['rollno']; ?>&name=<?php echo $row['name']; ?>&marks=<?php echo $row['marks']; ?>">View</a></th>
          <th><input type="checkbox" name="check[]" value="<?php echo $row['marks']; ?>" <?php if(isset($_POST['check']))  if (in_array($row['marks'], $_POST['check'])) echo "checked='checked'"; ?> /></th>
      </tr>
      <tr>
      <?php  } ?>
<input type ="submit" name="total" value="total">

And i am generating the total of marks of all the students

if(isset($_POST['total']))


{                        $t=0;
                     foreach($_REQUEST['check'] as $val)
                     {                             
                         $t=$t+$val;                             
                     }
               echo "    total : ".$t;


 }

Now problem is that when first time i run the program it displays 5 student's information and than i selected first two checkbox and press the "total" button to generate the total. So it displays the total properly and keep that two check boxes checked. But when i checked third checkbox and press the "total" button than it shows the total of that three selected check box's marks but it display 4th or last checkbox checked even if i did't checked it. So why that is happening. enter image description here See in above image- First i have selected checkbox of students a and b. so after pressing total it gave me total 2 and keep both the check boxes checked. Than i checked check box of student c and press the button "total" than it shows the total 4 properly. But makes the checkbox of student name "e" checked even if i didn't selected.




Angular 5 Checkbox in *ngFor Loop and get check and unchecked particular checkbox

Any Idea in Angular 5 where I have the checkbox in *ngFor loop so I want to know how this is getting the change in check and uncheck for the particular checkbox in *ngFor.

I have some code as below




How can I add a checkbox to a table that reads and writes the object property that it represents in JavaFX

I have a table that lists objects of type Bot which have a name and isOn properties that I want to list:

private SimpleStringProperty name;
private boolean isOn;

The boolean isOn, I want to be read from a checkbox and also editable from that checkbox

So far, I have been able to add a checkbox to a column in my table for each row but it is purely visual (i.e. it is not tied to the Bot's isOn member).

How can I make the checkbox read and write from and to this member of Bot?

Here is my code dealing with the Table altogether:

ObservableList<Bot> bots = FXCollections.observableArrayList();
@FXML
private TableView<Bot> botTable;
@FXML
private TableColumn<Bot, String> nameColumn;
@FXML
private TableColumn<Bot, Boolean> statusColumn;

public void initialize(URL location, ResourceBundle resources){
    nameColumn.setCellValueFactory(new PropertyValueFactory<Bot, String>("name"));
    statusColumn.setCellValueFactory(new PropertyValueFactory<Bot, Boolean>("on"));
    statusColumn.setSortable(false);

    statusColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Bot, Boolean>, ObservableValue<Boolean>>(){
        @Override public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Bot, Boolean> features) {
            return new SimpleBooleanProperty(features.getValue() != null);
        }
    });

    // create a cell value factory with an add button for each row in the table.
    statusColumn.setCellFactory(new Callback<TableColumn<Bot, Boolean>, TableCell<Bot, Boolean>>() {
        @Override public TableCell<Bot, Boolean> call(TableColumn<Bot, Boolean> personBooleanTableColumn) {
            return new AddBotCell(/*stage, botTable*/);
        }
    });

    botTable.setItems(bots);
}

/** A table cell containing a button for adding a new person. */
private class AddBotCell extends TableCell<Bot, Boolean> {
    // a button for adding a new person.
    final CheckBox checkbox = new CheckBox();
    // pads and centers the add button in the cell.
    final StackPane paddedCheckBox = new StackPane();
    // records the y pos of the last button press so that the add person dialog can be shown next to the cell.
    final DoubleProperty buttonY = new SimpleDoubleProperty();

    AddBotCell(/*final Stage stage, final TableView table*/) {
        paddedCheckBox.setPadding(new Insets(3));
        paddedCheckBox.getChildren().add(checkbox);
        checkbox.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
            }
        });
    }
    /** places an add button in the row only if the row is not empty. */
    @Override protected void updateItem(Boolean item, boolean empty) {
        super.updateItem(item, empty);
        if (!empty) {
            setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            setGraphic(checkbox);
        }
    }
}




mercredi 25 avril 2018

How to add checkbox in ng2-table in Angular-4?

I need to add checkbox in Angular 4 typescript we are using ng2-table.

//code for ng-table in html
<ng-table (tableChanged)="onChangeTable(config)"
(cellClicked)="onCellClick($event)"
[rows]="rows" [columns]="columns">
</ng-table>

//to create checkbox I am adding html in component where filling the data.
data.forEach((item: any) => 
{item.CheckBox = '<input type="checkbox"></input>';

//cell click event in table component is getting triggered
public onCellClick(data: any): any {
     this event is getting triggered
     ....
}

  1. Check box on UI is disabled or not able to checked. I think some event is getting triggered and reverting selected value to false each time. How to prevent that?
  2. Where do I bind this check box to ng-model or similar?

Please help. Thanks you.




How can I make angular material checkbox react to programmatic change of value in a reactive from?

I have a reactive angular form set up to be able to add rows via a button. I'd like to add the ability to select all rows.

Each row has a checkbox associated with it that changes the value in the object depending on its state (T or F). If all rows are checked, then the 'select all' checkbox becomes T else F. The issue is when I check the 'select all' checkbox, the value of all the rows changes to whatever the value of 'select all' is but their respective checkboxes remain unchanged. I'm using material angular checkbox.

I know with two-way data binding I could probably easily fix this but I'd like to know if there's a reactive form way of doing it.

      <div class="checkbox-container">
        <mat-checkbox formControlName="selected (change)="checkAllSelected()"></mat-checkbox>
      </div>
      <mat-form-field>
        <input matInput formControlName="name">
      </mat-form-field>




angular 5 reactive form checkbox sends object

In a reactive form, I need a checked box to send a typed object to the Typescript file and not just a string or a number. When I try using value= I get [object Object]. Is it possible to retrieve the correct object? Here is my template using Material Design:

<mat-selection-list formControlName="weapons">
<mat-list-option *ngFor="let weapon of selectedUnite.weapons" value=""></mat-list-option>
</mat-selection-list>

and the Typescript formGroup declaration:

this.uniteFormGroup = this._fb.group({
id: unite['id'],
name: unite['unite'],
size: unite['size'],
weapons: '',
staff: ''
});

Thanks a lot for your precious help!




Dont know where to place CheckBox Code in MainActivity.java

I am working on a quiz app, and ran into a basic problem, I want to implement a checkbox where if both answers are correct, the score should get updated, I don't know where to place the code in java

Basically this is how the app should work, total questions 5, each carrying 2 marks, three mcq in which one is correct , 4th question both answers are correct , so we add checkbox ,each checkbox carries one mark,then the editText field so that user can add his own comments, after all the questions are answered by user , then and only then , after clicking on the submit button , Score should be presented to user! Thankyou

Each question carries 2 marks, the problem is checkboxes are not working

MainActivity.java file here

    package com.example.android.quizatlast;

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

public class MainActivity extends AppCompatActivity {
    int Totalscore = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //toasts , onclick , and distroying buttons for next time


        final Button buttononeone = (Button) findViewById(R.id.Button1_1);
        final Button buttononetwo = (Button) findViewById(R.id.Button1_2);

        buttononeone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int score = 2;
                Totalscore = Totalscore + score;
                Score(Totalscore);
                buttononeone.setEnabled(false);
                buttononetwo.setEnabled(false);

            }
        });
        buttononetwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context context = getApplicationContext();
                CharSequence text = "Ahh,Wait for the score";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();

                buttononetwo.setEnabled(false);
                buttononeone.setEnabled(false);
            }
        });

        final Button buttontwoone = (Button) findViewById(R.id.Button2_1);
        final Button buttontwotwo = (Button) findViewById(R.id.Button2_2);

        buttontwoone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Context context = getApplicationContext();
                CharSequence text = "Dehli,City you should must visit";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                buttontwoone.setEnabled(false);
                buttontwotwo.setEnabled(false);

            }
        });

        buttontwotwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int score = 2;

                Totalscore = Totalscore + score;
                Score(Totalscore);

                Context context = getApplicationContext();
                CharSequence text = "Ahh,mumbai is  a beautiful place";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                buttontwotwo.setEnabled(false);
                buttontwoone.setEnabled(false);

            }
        });

        final Button buttonthreeone = (Button) findViewById(R.id.Button3_1);
        final Button buttonthreetwo = (Button) findViewById(R.id.Button3_2);
        buttonthreeone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int score = 2;

                Totalscore = Totalscore + score;
                Score(Totalscore);
                Context context = getApplicationContext();
                CharSequence text = "Agra , wonders are waiting there for you";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                buttonthreeone.setEnabled(false);
                buttonthreetwo.setEnabled(false);
            }
        });

                //PROBLEM HERE

        CheckBox checkBoxfourone = (CheckBox) findViewById(R.id.Checkbox4_1);
        boolean check4_1 = checkBoxfourone.isChecked();
        CheckBox checkBoxfourtwo = (CheckBox) findViewById(R.id.Checkbox4_2);
        boolean check4_2 = checkBoxfourtwo.isChecked();
        Score(Totalscore);
    }

    private int checkscore(boolean check4_1,boolean check4_2) {
        int score = Totalscore;
        if (check4_1) {
            Totalscore = Totalscore + 1;
        }
        if (check4_2) {
            Totalscore = Totalscore + 1;
        }
        return Totalscore;
    }

                //TILL HERE
    public void Score(int score) {

        TextView scoreView = (TextView) findViewById(R.id.score);
        scoreView.setText(String.valueOf(score));
    }public void reset(View view){
        Score(Totalscore = 0);
    }
}

activity_main.xml

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

<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="8dp"
    android:orientation="vertical"
    tools:context="com.example.android.justjava.MainActivity">

        <LinearLayout
            android:id="@+id/topping"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <EditText
                android:id="@+id/Name_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Name"
                android:inputType="textCapCharacters" />
            <EditText
                android:id="@+id/Email_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Email"
                android:inputType="textCapCharacters" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:text="Toppings"
                android:textSize="16sp"
                android:textAllCaps="true"/>
            <CheckBox
                android:id="@+id/checkbox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Whipped Cream"
                android:paddingLeft="24dp"
                android:textSize="16sp"
                android:layout_marginBottom="8dp"/>
            <CheckBox
                android:id="@+id/chocolate_checkbox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Chocolate"
                android:paddingLeft="24dp"
                android:textSize="16sp"
                android:layout_marginBottom="8dp"/>
        </LinearLayout>
        <TextView
            android:id="@+id/text_view"
            android:layout_below="@id/topping"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:text="quantity!"
            android:textAllCaps="true"
            android:textSize="16sp" />
        <LinearLayout
            android:id="@+id/linear"
            android:layout_below="@id/text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >   <Button
            android:onClick="decrement"        android:id="@+id/decrement"
            android:layout_below="@id/quantity_text_view"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:text="-"
            android:layout_marginBottom="8dp"/>


            <TextView
                android:layout_marginLeft="8dp"
                android:id="@+id/quantity_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_below="@id/increment"
                android:text="0"
                android:textColor="#000"
                android:layout_marginRight="8dp"
                android:textSize="24sp" />
            <Button
                android:onClick="increment"
                android:id="@+id/increment"
                android:layout_below="@id/text_view"
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:text="+"
                android:layout_marginBottom="8dp"/>

        </LinearLayout>

        <TextView
            android:id="@+id/order_summary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/linear"
            android:layout_marginBottom="8dp"
            android:text="order summary"
            android:textAllCaps="true"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/order_summary_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/order_summary"
            android:layout_marginBottom="8dp"
            android:textSize="24sp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/order_summary_text_view"
            android:onClick="submitOrder"
            android:text="order" />


    </LinearLayout>
</ScrollView>




Disable submit button of form_tag, if no check box is enabled

I am using the form_tag to delete multiple records at a time, same as described here : Rails 3 - Delete Multiple Records Using Checkboxes. I want to disable the submit button if no checkbox is checked and enable it as soon we check any of these button. Tried multiple solution, but not worked




mardi 24 avril 2018

CheckBox updating Progress Bar does not load

Application simply says "Unfortunately stopped working" on device. Each checkbox needs to update the progress bar percentage. For some reason the app will not deploy and I have no idea if the code I am using is functional or appropriate. Any advice will be appreciated very much on how to get this concept functioning!

package com.example.thomas.progressbar;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ProgressBar;

public class ProgressBars extends AppCompatActivity {

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


    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
    final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
    final CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
    final CheckBox checkBox3 = (CheckBox) findViewById(R.id.checkBox3);
    final CheckBox checkBox4 = (CheckBox) findViewById(R.id.checkBox4);
    final CheckBox checkBox5 = (CheckBox) findViewById(R.id.checkBox5);


    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    final SharedPreferences.Editor editor = preferences.edit();
    if (preferences.contains("checkbox1") && preferences.getBoolean("checkbox1", false) == true) {
        checkBox.setChecked(true);
    } else {
        checkBox.setChecked(false);

    }
    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (checkBox.isChecked()) {
                editor.putBoolean("checkbox1", true);
                progressBar.setProgress(20);
                editor.apply();
            } else {
                editor.putBoolean("checkbox1", false);
                progressBar.setProgress(-20);
                editor.apply();
            }
        }
    });


    if (preferences.contains("checkbox2") && preferences.getBoolean("checkbox2", false) == true) {
        checkBox2.setChecked(true);
    } else {
        checkBox2.setChecked(false);

    }
    checkBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (checkBox2.isChecked()) {
                editor.putBoolean("checkbox2", true);
                progressBar.setProgress(20);
                editor.apply();
            } else {
                editor.putBoolean("checkbox2", false);
                progressBar.setProgress(-20);
                editor.apply();
            }
        }
    });


    if (preferences.contains("checkbox3") && preferences.getBoolean("checkbox3", false) == true) {
        checkBox3.setChecked(true);
    } else {
        checkBox3.setChecked(false);

    }
    checkBox3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (checkBox3.isChecked()) {
                editor.putBoolean("checkbox3", true);
                progressBar.setProgress(20);
                editor.apply();
            } else {
                editor.putBoolean("checkbox3", false);
                progressBar.setProgress(-20);
                editor.apply();
            }
        }
    });

    if (preferences.contains("checkbox4") && preferences.getBoolean("checkbox4", false) == true) {
        checkBox4.setChecked(true);
    } else {
        checkBox4.setChecked(false);

    }
    checkBox4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (checkBox4.isChecked()) {
                editor.putBoolean("checkbox4", true);
                progressBar.setProgress(20);
                editor.apply();
            } else {
                editor.putBoolean("checkbox4", false);
                progressBar.setProgress(-20);
                editor.apply();
            }
        }
    });

    if (preferences.contains("checkbox5") && preferences.getBoolean("checkbox5", false) == true) {
        checkBox5.setChecked(true);
    } else {
        checkBox5.setChecked(false);

    }
    checkBox5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (checkBox5.isChecked()) {
                editor.putBoolean("checkbox5", true);
                progressBar.setProgress(20);
                editor.apply();
            } else {
                editor.putBoolean("checkbox5", false);
                progressBar.setProgress(-20);
                editor.apply();
            }
        }
    });

}
}

Here is the XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.thomas.progressbar.ProgressBars">


<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="20dp"
    android:layout_marginTop="84dp"
    android:text="CheckBox" />

<CheckBox
    android:id="@+id/checkBox2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/checkBox"
    android:layout_below="@+id/checkBox"
    android:layout_marginStart="12dp"
    android:layout_marginTop="48dp"
    android:text="CheckBox" />

<CheckBox
    android:id="@+id/checkBox3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/checkBox2"
    android:layout_centerVertical="true"
    android:text="CheckBox" />

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

<CheckBox
    android:id="@+id/checkBox5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/checkBox3"
    android:layout_below="@+id/checkBox3"
    android:layout_marginTop="64dp"
    android:text="CheckBox" />

<Button
    android:id="@+id/compoundButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/checkBox5"
    android:layout_marginStart="27dp"
    android:layout_toEndOf="@+id/progressBar"
    android:text="Button" />

<ProgressBar
    android:id="@+id/progressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/compoundButton"
    android:layout_marginStart="62dp"
    android:layout_marginTop="12dp"
    android:layout_toEndOf="@+id/checkBox5" />
</RelativeLayout>




Store dynamically created checkbox value in another table in Laravel

I have the following code to dynamically generate check-boxes from one table:

{!! Form::open(['url' =>URL::to('admin/user/'.$profileUser->id) , 'method'=>'PUT', 'enctype'=>'multipart/form-data' ]) !!}
                    @foreach ($userRoles as $key => $userRole)
                    <tr>
                        <td width="10%"></td>
                        <td></td>
                    </tr>
                    @endforeach
                    <tr></tr>
            </tbody>
            

In the controller I have:

    if (isset($_POST['roleSubmit'])){
        DB::table('role_users')->where('user_id', $request->get('id', $id))->delete();


        $userRole = json_encode($request->input('rolename'));
        DB::table('role_users')->insert(
            array(
                'user_id' => $id,
                'role_id' => $userRole
            )
        );
        return redirect()->back();
    }

I need to dynamically generate multiple checkboxes from 'roles' tableenter image description here

and display like this: enter image description here

Then I need to store the checkbox values in 'role_users' like this:enter image description here

Instead, for the above snippet of code, I am getting this: enter image description here

Any guideline where I am messing it?




Javascript message

I am having some problems fixing my JS code. In the snippet code you can see my program,

Now click the first checkbox. A message appears at the bottem, as soon as I type a number in it the message should dissapear and the textbox should not disable ...

When I click a second checkbox the message should append to the previous, but it just overwrites... and then with the same values as the previous one ...

Can anyone give me some idea's about that? Should be something wrong in the test function ...

Thank you in advance.

// JavaScript source code

// ************ arrays *************

var aoCursus = [
    { cursusnaam: "houtsoorten herkennen", duurtijd: "4 weken", prijs: 259 },
    { cursusnaam: "planken zagen", duurtijd: "4 dagen", prijs: 138 },
    { cursusnaam: "parketvloer leggen", duurtijd: "2 dagen", prijs: 57 },
    { cursusnaam: "hout beitsen", duurtijd: "4 uren", prijs: 21 },
    { cursusnaam: "houtbewerking", duurtijd: "2 weken", prijs: 204 }];

var aHoutSoorten = [
    ["bangkirai", "stuks"],
    ["beukenhout", "stuks"],
    ["dennenhout", "stuks"],
    ["eikenhout", "stuks"],
    ["kastanjehout", "stuks"],
    ["lindehout", "stuks"],
    ["notenhout", "stuks"],
    ["rubberhout", "stuks"],
    ["Cederhout", "kg"]];

var nCursus = aoCursus.length;
var nHout = aHoutSoorten.length;



window.onload = function () {


    // dropdownlijst

    var eCursus = document.getElementById('woodcursus');

    // form wordt nu altijd gecancelled, nog in een if then .... gieten
    const element = document.querySelector('form');
    element.addEventListener('submit', event => {
        event.preventDefault();
        // actual logic, e.g. validate the form
        console.log('Form submission cancelled.');
        alert('Form submission cancelled.');
    });
}; // einde onload


function test(el)
{
    divOutput = document.getElementById("msgbox2");
    strValideer = "<ul>";
    var txt = document.getElementById(el.id.replace('chk', 'txt'))
    if (el.checked === true ) {
        txt.disabled = false;
        if(txt.value==="")
        {
            strValideer += "<li><b>" + txt.name + ": </b>verplicht veld</li>";
        }
        }
    else if (el.checked === false)
    {
        txt.disabled = true;
      return;

    }

    strValideer += "</ul>";
    divOutput.innerHTML = strValideer;
}





function valideer() {
    divOutput = document.getElementById("msgbox1");
    var strValideer = "<ul>";

    if (document.getElementById("naam").value === "") {
        strValideer += "<li><b>naam</b>: verplicht veld</li>";
    } if (document.getElementById("voornaam").value === "") {
        strValideer += "<li><b>voornaam</b>: verplicht veld</li>";
    } if (document.getElementById("straatnr").value === "") {
        strValideer += "<li><b>straat en nummer</b>: verplicht veld</li>";
    } if (document.getElementById("postgem").selectedIndex === 0) {
        strValideer += "<li><b>gemeente</b>: verplicht veld</li>";
    } if (document.getElementById("telgsm").value === "") {
        strValideer += "<li><b>nummer</b>: verplicht veld</li>";
    } if (document.getElementById("email").value === "") {
        strValideer += "<li><b>mail</b>: verplicht veld</li>";
    }
    strValideer += "</ul>";
    divOutput.innerHTML = strValideer;
}

function berekenPrijsenTijd() {
    divOutput = document.getElementById("msgbox3");
    strValideer = "<ul>";

    if (document.getElementById("woodcursus").selectedIndex === 1) {
        strValideer += "<li><b>duurtijd: </b> " + aoCursus[0].duurtijd + ", prijs: " + aoCursus[0].prijs + "</li>";
    }
    if (document.getElementById("woodcursus").selectedIndex === 2) {
        strValideer += "<li><b>duurtijd: </b> " + aoCursus[1].duurtijd + ", prijs: " + aoCursus[1].prijs + "</li>";
    }
    if (document.getElementById("woodcursus").selectedIndex === 3) {
        strValideer += "<li><b>duurtijd: </b> " + aoCursus[2].duurtijd + ", prijs: " + aoCursus[2].prijs + "</li>";
    }
    if (document.getElementById("woodcursus").selectedIndex === 4) {
        strValideer += "<li><b>duurtijd: </b> " + aoCursus[3].duurtijd + ", prijs: " + aoCursus[3].prijs + "</li>";
    }
    if (document.getElementById("woodcursus").selectedIndex === 5) {
        strValideer += "<li><b>duurtijd: </b> " + aoCursus[4].duurtijd + ", prijs: " + aoCursus[4].prijs + "</li>";
    }
    if (document.getElementById("woodcursus").selectedIndex === 6) {
        strValideer += "<li><b>duurtijd: </b> " + aoCursus[5].duurtijd + ", prijs: " + aoCursus[5].prijs + "</li>";
    }

    strValideer += "</ul>";
    divOutput.innerHTML = strValideer;
}
<fieldset>
                <legend>Bestel gegevens</legend>
                <div class="container">
                    <div class="row">
                        <div class="span7" id="houtsoorten">
                            <div class="control-group">
                                <label class="control-label">
                                    bangkirai
                                    <input id="chkbangkirai" type="checkbox" onchange="test(this)" >
                                </label>
                                <div class="controls">
                                    <div class="input-append">
                                        <input class="inpbox input-mini" type="text" id="txtbangkirai" name="bangkirai" placeholder="aantal" disabled oninput="test(this)">
                                        <span class="add-on">stuks</span>
                                    </div>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">
                                    beukenhout
                                    <input id="chkbeukenhout" type="checkbox" onchange="test(this)">
                                </label>
                                <div class="controls">
                                    <div class="input-append">
                                        <input class="inpbox input-mini" type="text" id="txtbeukenhout" name="beukenhout" placeholder="aantal" disabled oninupt="test(this)">
                                        <span class="add-on">stuks</span>
                                    </div>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">
                                    dennenhout
                                    <input id="chkdennenhout" type="checkbox" onchange="test(this)">
                                </label>
                                <div class="controls">
                                    <div class="input-append">
                                        <input class="inpbox input-mini" type="text" id="txtdennenhout" name="dennenhout" placeholder="aantal" disabled oninput="test(this)">
                                        <span class="add-on">stuks</span>
                                    </div>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">
                                    eikenhout
                                    <input id="chkeikenhout" type="checkbox" onclick="test(this)">
                                </label>
                                <div class="controls">
                                    <div class="input-append">
                                        <input class="inpbox input-mini" type="text" id="txteikenhout" name="eikenhout" placeholder="aantal" disabled oninput="test(this)">
                                        <span class="add-on">stuks</span>
                                    </div>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">
                                    kastanjehout
                                    <input id="chkkastanjehout" type="checkbox" onchange="test(this)">
                                </label>
                                <div class="controls">
                                    <div class="input-append">
                                        <input class="inpbox input-mini" type="text" id="txtkastanjehout" name="kastanjehout" placeholder="aantal" disabled oninput="test(this)">
                                        <span class="add-on">stuks</span>
                                    </div>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">
                                    lindehout
                                    <input id="chklindehout" type="checkbox" onchange="test(this)">
                                </label>
                                <div class="controls">
                                    <div class="input-append">
                                        <input class="inpbox input-mini" type="text" id="txtlindehout" name="lindehout" placeholder="aantal" disabled oninput="test(this)">
                                        <span class="add-on">stuks</span>
                                    </div>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">
                                    notenhout
                                    <input id="chknotenhout" type="checkbox" onchange="test(this)">
                                </label>
                                <div class="controls">
                                    <div class="input-append inline">
                                        <input class="inpbox input-mini" type="text" id="txtnotenhout" name="notenhout" placeholder="aantal" disabled oninput="test(this)">
                                        <span class="add-on">stuks</span>
                                    </div>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">
                                    rubberhout
                                    <input id="chkrubberhout" type="checkbox" onchange="test(this)">
                                </label>
                                <div class="controls">
                                    <div class="input-append inline">
                                        <input class="inpbox input-mini" type="text" id="txtrubberhout" name="rubberhout" placeholder="aantal" disabled oninput="test(this)">
                                        <span class="add-on">stuks</span>
                                    </div>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">
                                    Cederhout
                                    <input id="chkCederhout" type="checkbox" onchange="test(this)">
                                </label>
                                <div class="controls">
                                    <div class="input-append inline">
                                        <input class="inpbox input-mini" type="text" id="txtCederhout" name="Cederhout" placeholder="kg" disabled oninput="test(this)">
                                        <span class="add-on">kg</span>
                                    </div>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">betalingswijze</label>
                                <div class="controls">
                                    <label class="radio">
                                        <input type="radio" name="optionsRadios" id="visa" value="visa">
                                        visa
                                    </label>
                                    <label class="radio">
                                        <input type="radio" name="optionsRadios" id="overschrijving" value="overschrijving">
                                        overschrijving
                                    </label>
                                    <label class="radio">
                                        <input type="radio" name="optionsRadios" id="cash" value="cash">
                                        cash
                                    </label>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">opmerkingen:</label>
                                <div class="controls">
                                    <textarea rows="5" placeholder="opmerkingen"></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="span4 valid">
                            <div id="msgbox2" class="alert alert-error" style="display: block;">validatie bestelgegevens verschijnt hier
                        </div>
                        <div class="span1"><!--lege kolom--></div>
                        <!--einde row-->
                    </div>
                    <!--einde container-->
                  </div>
                </div>
            </fieldset>