samedi 30 avril 2016

Function to change checkboxes not working on dynamically created table

I have a table that each row has three checkboxes, what I am trying to do is have it so only one checkbox can be selected per row. If a checkbox is checked, the other checkboxes will be unchecked. The code that I currently have is the following:

$('#idCheckboxOne').on 'change', ->
  if $('#idCheckboxOne').prop('checked')
    $('#idCheckboxTwo').prop 'checked', false
    $('#idCheckboxThree').prop 'checked', false

$('#idCheckboxTwo').on 'change', ->
  if $('#idCheckboxTwo').prop('checked')
    $('#idCheckboxOne').prop 'checked', false
    $('#idCheckboxThree').prop 'checked', false

$('#idCheckboxThree').on 'change', ->
  if $('#idCheckboxThree').prop('checked')
    $('#idCheckboxTwo').prop 'checked', false
    $('#idCheckboxOne').prop 'checked', false

So this code will work on the first row of my table, but not any other row. I know that part of my problem is that Im using the function by the checkbox's ids, so since each table row has the same checkboxes, the ids are not unique for the other table rows. So my question is what is the best approad for having the above functionality for each table row?




i want to decrease count when already checked checkbox is unchecked. how do i do this?

i was trying to make a list that will select only 3 symptoms. for which i put a while loop that stops when count becomes 3. count increases when a checkbox is checked but it doesn't decrease when it is unchecked again. How do i solve this. here is what i have done so far:-

JAVA CODE

public void onCheckboxClick (View view) {
        int count = 0;
        String a, b, c;
        CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
        CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
        CheckBox checkBox3 = (CheckBox) findViewById(R.id.checkBox3);
        CheckBox checkBox4 = (CheckBox) findViewById(R.id.checkBox4);
        CheckBox checkBox5 = (CheckBox) findViewById(R.id.checkBox5);
        while(count<3){
            switch (view.getId()) {
                case R.id.checkBox1:
                     if (checkBox1.isChecked()) {
                        if (count == 0) {
                           a = "Bad taste in mouth";
                        } else if (count == 1) {
                        b = "Bad taste in mouth";
                        } else if (count == 2) {
                        c = "Bad taste in mouth";
                     }
                     count++;
                     } else {

                     }
                     break;
                case R.id.checkBox2:
                     if (checkBox2.isChecked()) {
                        if (count == 0) {
                           a = "Gap in between teeth";
                        } else if (count == 1) {
                           b = "Gap in between teeth";
                        } else if (count == 2) {
                           c = "Gap in between teeth";
                     }  
                     count++;
                     } else {

                     }
                     break;
                case R.id.checkBox3:
                     if (checkBox3.isChecked()) {
                        if (count == 0) {
                        a = "Bad breath";
                     } else if (count == 1) {
                        b = "Bad breath";
                     } else if (count == 2) {
                        c = "Bad breath";
                     }
                     count++;
                     } else {

                     }
                     break;
                case R.id.checkBox4:
                     if (checkBox4.isChecked()) {
                        if (count == 0) {
                           a = "Nasal pain";
                        } else if (count == 1) {
                           b = "Nasal pain";
                        } else if (count == 2) {
                           c = "Nasal pain";
                        }
                     count++;
                     } else {

                     }
                     break;
                case R.id.checkBox5:
                     if (checkBox5.isChecked()) {
                        if (count == 0) {
                           a = "Blurred vision";
                        } else if (count == 1) {
                           b = "Blurred vision";
                        } else if (count == 2) {
                           c = "Blurred vision";
                        }
                        count++;

                     } else {

                     }
                     break;
            }
        }
}

XML CODE

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bad taste in mouth"
        android:id="@+id/checkBox1"
        android:onClick="onCheckboxClick"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Gap in between teeth"
        android:id="@+id/checkBox2"
        android:onClick="onCheckboxClick"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bad breath"
        android:id="@+id/checkBox3"
        android:onClick="onCheckboxClick"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Nasal pain"
        android:id="@+id/checkBox4"
        android:onClick="onCheckboxClick"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Blurred vision"
        android:id="@+id/checkBox5"
        android:onClick="onCheckboxClick"/>

Any help will be appreciated thank you :)




Checkbox select and delete from database

I have multiple checkbox and button in my form. When I select one or more checkboxes and press button I saved all values in the database.

Now I need select that values from database and checkbox must be checked only for values that are in database, and on unchecked i must delete data from database and after page reload checkbox must be unchecked.. how can i simple write this code?

I have in java servlet class input in database and its works.

Thank you.

//checkbox from form 

     "<td><span>checkbox:</span><input class='chxActivate' type='checkbox' id='ID_"+p.getID()+"' name='ID_"+p.getID()+"' value='1'></td>"



//servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    Connection c = null;
    Statement stmt = null;

    Set<String> parameterNames = request.getParameterMap().keySet();
    for (String string : parameterNames) {
        System.out.println(string);
    }

    Enumeration<String> en = request.getParameterNames(); 
    Integer tmpsnlid = null;
    String auxStr = "";

    while (en.hasMoreElements()) {
        auxStr = (String) en.nextElement();
        if (auxStr.startsWith("ID_")){
                tmpsnlid = Integer.parseInt(auxStr.substring(6));   
                System.out.println("V2) Checkbox postavljen: "+tmpsnlid);
                try {
                      Class.forName("org.postgresql.Driver");
                      c = DriverManager.getConnection("jdbc:postgresql://database", "user","pass");
                      c.setAutoCommit(false);
                      System.out.println("Opened database successfully");
                      stmt = c.createStatement();
                      String sql = "INSERT INTO database(id, active, username)" +
                                   "VALUES ('"+tmpsnlid+"', 't','kavusladnin');"; 
                      stmt.executeUpdate(sql);
                      stmt.close();
                      c.commit();
                      c.close();
                    } catch ( Exception e ) {
                      System.err.println( e.getClass().getName()+ ": " + e.getMessage() );
                      System.exit(0);
                    }
                    System.out.println("INSERT - Records created successfully");

        }
    }




Treeview + DB | SQL requests for filter data

In my ASP.net MVC project I have problems with implementation of TreeView (with Checkbox) which connected with Database.

QUESTIONS:

1) How to realise Treeview with such structure as in the second picture?! I am really confused with right SQL requests.

2) Is it possible to use a pure sql query for CheckBoxes in Treeview below to filter the table. For example the second checkbox corresponds to the query:

select termID, termCode, termname
from coltermtree, terms
where  coltermID=30 and parentnodeID=10

I just want to say that when user choose CheckBoxs which he want and click "Search" button he will see information from DB tables in "Content" block.

In the picture below you can see the structure of database: enter image description here

Treeview (with CheckBox) must be like this (RESULT): enter image description here




Need help in GUI

For button Back and button Delete, I have setBounds to (130, 120, 195,30); and (10, 190, 195,30); , but they still doesn't move to bottom.

What's wrong here ?

enter image description here

public deleteAdmin(int num)
    {
        super("Delete Admin");
        setBounds(100, 200, 340, 229);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        panel.setBounds(35, 19, 242, 146);
        contentPane.add(panel);

        JButton button = new JButton("Back");
        button.setBounds(130, 120, 195,30);
        panel.add(button);

        JButton bckButton = new JButton("Delete");
        bckButton.setBounds(10, 190, 195,30);
        panel.add(bckButton);

        adminAPI admin = new adminAPI();
        List<String>allName = null;
        try {
            allName= admin.displayName();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //System.out.println(allName);
        Object [] o1=allName.toArray();
        JCheckBox[] checkBoxList = new JCheckBox[num];
        System.out.println(allName);
         //JLabel[] names = new JLabel[num];
        for(int i = 0; i < num; i++) {   
            checkBoxList[i] = new JCheckBox(""+o1[i]);
            System.out.println(o1[i]);
           contentPane.add(checkBoxList[i]);

        }


    }




Android CheckBox text moves up when checked

I create a simple form inside an activity which user can select some items by checking the corresponding CheckBoxes and everythings act normal in runtime. After adding this layout into a TabHost by including the layout, checkbox text goes up when touched (i.e. just like setting gravity to up). I have tried to correct this issue by overriding checkbox text gravity in onCheckedChangeListener but it seems that the problem is not related to gravity.

this is how I have included the layout to tabhost:

<TabHost
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tabHost"
    android:layout_below="@id/my_toolbar" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"></TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:id="@+id/tab1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <include
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    layout="@layout/activity_main"
                    android:id="@+id/tab1Layout" />
            </LinearLayout>

and this is activity main layout:

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/answer0TL"
    android:layout_below="@id/info0TextView" >

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/one0TR">

        <CheckBox
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="Food"
            android:id="@+id/foodCheckBox"
            android:layout_weight="1" />

        <CheckBox
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="Dinning out / Restaurants"
            android:id="@+id/restaurantsCheckBox"
            android:layout_weight="1" />
    </TableRow>

What is wrong with this code?




java - add in checkbox

I am creating a pizza ordering system. As of now I had a stroller in order to select the toppings but I want to change to check boxes so I can elect multiple values at once without using ctrl. The problem is though I really have no idea how to use them. I never had to use them before. Can someone please show me how it is done. Thank you here is the code:

 package loan;

import javafx.application.Application;
import javafx.collections.*;
    import javafx.event.*;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
    import javafx.stage.Stage;
    import javafx.scene.layout.*;
    import javafx.scene.paint.Color;
    import javafx.scene.control.*;
    import javafx.scene.Scene;
    import javafx.scene.shape.*;
    import javafx.scene.paint.*;

    public class pizzas extends Application{
        private ComboBox<String> size;
        private ListView<String> toppings;
        private TextField order;
        private Button orderit, clearit;
        private Label lb_size, lb_tops, lb_order;
        private ObservableList<String> flavor =
                FXCollections.observableArrayList (
                        "Small", "Medium",
                        "Large", "extra Large");
        private ObservableList<String> tps =
                FXCollections.observableArrayList(
                        "pineapples", "pepperoni",
                        "peppers", "bacon", "sausage",
                        "ham");
        public void start(Stage primaryStage) {
            //areas to place the various components
            VBox pane = new VBox(15);
            HBox flavor_pane = new HBox(10);
            HBox topping_pane = new HBox(10);
            HBox order_pane = new HBox(10);

            lb_size = new Label("Sizes");
            size = new ComboBox(flavor);
            size.setVisibleRowCount(4);
            size.setValue(flavor.get(0)); // display the first one

            flavor_pane.getChildren().addAll(lb_size, size);

            //lb_tops = new Label("toppings");
            //toppings = new ListView(tps);
            //toppings.setPrefSize(100,80);
    //toppings.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

               //topping_pane.getChildren().addAll(lb_tops, toppings);

            lb_order = new Label("Order Summary");
            order = new TextField();
            order.setEditable(false);
            order.setPrefColumnCount(25);

            order_pane.getChildren().addAll(lb_order, order);

            orderit = new Button("Place Order");
            clearit = new Button("Clear Order");

            // Subscribe for when the user clicks the buttons
            OrderHandler oh = new OrderHandler();
            orderit.setOnAction(oh);
            clearit.setOnAction(oh);

            pane.getChildren().addAll(flavor_pane,
                    topping_pane, order_pane, orderit, clearit);

            Scene scene = new Scene(pane, 400, 300);
            primaryStage.setTitle("pizza ordering");
            primaryStage.setScene(scene);
            primaryStage.show();

        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Application.launch(args);
        }
    class OrderHandler implements EventHandler<ActionEvent>{
        public void handle(ActionEvent e) {
            // was it the clear button  
            if (e.getSource() == clearit) {
                order.setText("");
                toppings.getSelectionModel().clearSelection();
                size.setValue(flavor.get(0));
                System.out.println("the order has been cancelled. No order will be made.");
                return;
            }
            // flavor
            String result = size.getValue();
            // for toppings
            ObservableList<String> selections =
            toppings.getSelectionModel().getSelectedItems();
            // convert to an array
            Object[] objs = selections.toArray();
            for (int k =0 ; k < objs.length; k++){
                result += " " + objs[k].toString();
            }
            order.setText(result);
        }
    }
    }

As of now. I commented out the lines that created the toppings stroller.When I start the program I select the size and once i press order it appears in the order summary.




Android: How to fix accidental uncheck the checkbox of the parent node in the tree

I wrote the class to represent a tree file hierarchy. The main task - the ability to mark files and folders (using the checkbox). Has faced with such a problem: disappears check mark of the parent directory with the following sequence of actions:

0) Go to the root directory, check file (leave one directory unchecked)

1) Go to the unchecked directory and check any file (or more)

2) Return to a higher level and uncheck the directory,in which was carried out operation (1)

Return to a higher level and you'll see that check mark of the parent directory is unchecked (although there is at least one checked file in a root directory).

For many days I am in search of a problem. Maybe someone will notice the error. Thank you in advance.

Screenshots:

Bug

Normal state

The class:

public class FileTree {
    /* The name for pointer to the parent node */
    public static final String PARENT_DIR = "..";

    private String mName;
    private boolean mIsLeaf;
    private boolean mIsChecked = false;
    private long mSize;
    /* Number of checked children */
    private int childrenCheckNum = 0;
    private FileTree mParent;
    private Map<String, FileTree> mChildren = new LinkedHashMap<String, FileTree>();

    public FileTree(String name, long size, int type)
    {
        this(name, size, type, null);
    }

    public FileTree(String name, long size, int type, FileTree parent)
    {
        mName = name;
        mIsLeaf = type == FileNode.Type.FILE;
        mParent = parent;
        mSize = size;
    }

    public void addChild(FileTree node)
    {
        if (!mChildren.containsKey(node.getName())) {
            mChildren.put(node.getName(), node);
            mSize += node.size();
            if (mParent != null) {
                mParent.onChildAdd(node.size());
            }
        }
    }

    /*
     * Sending new child size up the tree.
     */

    private void onChildAdd(long size)
    {
        mSize += size;
        if (mParent != null) {
            mParent.onChildAdd(size);
        }
    }

    public boolean findChild(String name)
    {
        if (mChildren.containsKey(name)) {
            return true;
        }

        return false;
    }

    ...

    public boolean isChecked()
    {
        return mIsChecked;
    }

    public void setCheck(boolean check)
    {
        mIsChecked = check;

        /* Sending check change event up the parent */
        if (mParent != null && mParent.isChecked() != check) {
            mParent.onChildCheckChange(check);
        }

        /* Sending check change event down the tree */
        if (getChildrenCount() != 0) {
            childrenCheckNum = check ? getChildrenCount() : 0;

            for (FileTree node : mChildren.values()) {
                if (node.isChecked() != check) {
                    node.setCheck(check);
                }
            }
        }
    }

    /*
     * Sending check change events up the tree.
     */

    private void onChildCheckChange(boolean check)
    {
        if (check) {
            ++childrenCheckNum;
            mIsChecked = true;
        } else {
            if (childrenCheckNum > 0) {
                --childrenCheckNum;
            }

            /* Uncheck parent only if don't left selected children nodes */
            if (childrenCheckNum == 0) {
                mIsChecked = false;
            }
        }

        /* Sending check change event up the parent */
        if (mParent != null && mParent.isChecked() != check) {
            mParent.onChildCheckChange(check);
        }
    }
    ...
}




Angularjs scope variable not updating as expected

Here is the Plunker Preview of the problem.

Index.html

 <body ng-controller="MainCtrl">

Master Checkbox : <input type="checkbox" id="allSelected" ng-click="checkAll('allSelected')"  ng-checked="allChecked"> <br> <br>

Slave1 : <input type="checkbox" id="slave1" ng-click="checkAll('slave1')" ng-checked="selectedAll" > <br>
Slave2 : <input type="checkbox" id="slave2" ng-click="checkAll('slave2')" ng-checked="selectedAll" > <br>
Slave3 : <input type="checkbox" id="slave3" ng-click="checkAll('slave3')" ng-checked="selectedAll" > <br>
Slave4 : <input type="checkbox" id="slave4" ng-click="checkAll('slave4')" ng-checked="selectedAll" > <br>
Slave5 : <input type="checkbox" id="slave5" ng-click="checkAll('slave5')" ng-checked="selectedAll" > <br>

app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.checkAll = function(id) {

    // First Condition
    if (id === "allSelected" && document.getElementById(id).checked) {
     // $scope.selectedAll = false;
      $scope.allChecked = true;
      $scope.selectedAll = true;
    }

    // Second Condition
    if (id === "allSelected" && !document.getElementById(id).checked) {
      $scope.allChecked = false;
      $scope.selectedAll = false;
    }

    // Third Condition
    if (id !== "allSelected" && !document.getElementById(id).checked) {
      $scope.allChecked = false;

    }


  };
});

See the First Condition. It is not working as expected.

I'm uploading images here for a better understanding of the problem.

This is working as expected but after this

this is not working as expected

Checkout the difference between first image and second image. After unchecking any of the slave checkbox, the master checkbox is getting unchecked but just after that when you click the master checkbox again(see the second image) that particular salve checkbox is still unchecked. Why?

What I'm doing here is wrong? How to make this code working as expected?




How do I get each checkbox to have one name?

I wanted to make checkboxes and names added dynamically. The number of checkboxes is follow the number of row in MySQL and the name is retrieved from MySQL.

So far, the checkboxes can add dynamically but the problem is I have no idea on how to break the names so that each checkbox only have one name.

This is what I want to archive.

enter image description here

This is the output I get

enter image description here

Eerything start with staffManagement

adminAPI api= new adminAPI();
         try {
            num= api.displayCheckBoxAndLabel(); // there are 5 row
            //allName= api.displayName();
            //System.out.println(allName);

        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }    
        deleteAdmin delete= new deleteAdmin(num);
        delete.setVisible(true);
        setVisible(false);
        dispose();

adminAPI

public int displayCheckBoxAndLabel() throws Exception
    {
        int count = 0;
        String sql="Select count(*) AS adminID from admin";
        DatabaseConnection db = new DatabaseConnection();
        Connection  conn =db.getConnection();
        PreparedStatement  ps = conn.prepareStatement(sql);
         ResultSet rs = ps.executeQuery();
         while(rs.next()) 
         {  
             count= rs.getInt("adminID");

         }
         ps.close();
         rs.close();
         conn.close();
         return count ;
    }

    public List<String> displayName() throws Exception // get all the name
    {
        String sql = "Select name from admin";
        List<String> names = new ArrayList<>();
        DatabaseConnection db = new DatabaseConnection();
        try (Connection conn = db.getConnection();
                PreparedStatement ps = conn.prepareStatement(sql);
                ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                names.add(rs.getString("name"));
            }
        }
        return names;
    }

deleteAdmin

public deleteAdmin(int num)
    {
        super("Delete Admin");
        setBounds(100, 200, 340, 229);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        panel.setBounds(35, 19, 242, 146);
        contentPane.add(panel);
        panel.setLayout(null);

        adminAPI admin = new adminAPI();
        List<String>allName = null;
        try {
            allName= admin.displayName();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(allName); //[john,1,1,23,sd]

        JCheckBox[] checkBoxList = new JCheckBox[num];

        for(int i = 0; i < num; i++) {
            checkBoxList[i] = new JCheckBox(""+allName);
           contentPane.add(checkBoxList[i]);

        }


    }

How can I break the arrayList so each checkbox will only have one name? Thanks




MixItUp: Clear filters per group

In my project I'm using MixItUp and found this particular code example:

http://ift.tt/1N9JWYr

self.$reset.on('click', function(e){
  e.preventDefault();
  self.$filterUi[0].reset();
  self.$filterUi.find('input[type="text"]').val('');
  self.parseFilters();
});

I assume the above snippet is what you need to look at.

I'd really like to know how I can add an extra checkbox per filter group (in each column) that will act as a 'filter none'/'show all' filter for that particular group.

This checkbox should be checked by default (the others unchecked) and be unchecked when one or more checkboxes from that group are checked instead. Unchecking all checked non-'show-all' checkboxes should then again check the 'show-all' checkbox of that group.

In the code example above, you may ignore the search field and clear button. In fact, the 'show all' checkbox that I'd like each group to have should function the same as the clear filters button from the example but on a per-group basis.

Another example I found has similar functionality but uses dropdowns for each group, which is not an option for my project:

http://ift.tt/1QGEWVY

If someone can somehow combine these two to have checkboxes and clear buttons per group, that'd would be highly appreciated.




vendredi 29 avril 2016

Android: Dynamically show all checkboxes in adapter onLongClick

I was learning custom adapter concepts recently.

Problem is during onlongClick in a row, I want to show checkboxes checked in the longclicked row, which is in android:visibility="gone" initially. And also to show checkboxes in other rows which are not clicked in unchecked state.

I changed some parts of this code here. http://ift.tt/1TauxU1

In simplerow.xml I made android:visibility="gone" initially.

Now I made a onLongClickListener inside getView(...) method

textView.setOnLongClickListener (new View.OnLongClickListener() {
     @Override
     public boolean onLongClick(View v) {
         CheckBox cb = (CheckBox) v;
         Planet planet = (Planet) cb.getTag();  
         planet.setVisibility(View.VISIBLE);
         planet.setChecked(true);
     }
});

Now the above code will affect only the longClicked row. How do I make changes in the non-clicked rows?

Calling notifyDataSetChanged() on long click did not work because the other rows have checkbox initially in android:visibility="gone".

Please help. Is any other work around possible?




Toggle class for CheckBoxes plus validations

I have a LOT of checkboxes, 95. They all have hte same class and are named as an array. I need to change the class from bg-primary to bg-success or some other color. I also need to be able to say at the end, 'You missed this checkbox'. this is where I am at now

   <h3 class = "col-lg-12 text-center bg-warning "><a href="#">STEP 5 - Under the hood</a></h3>
    <div id= "acc4">
   <form>
     <fieldset class="form-horizontal form-group bg-primary">   
        <input type="checkbox" class="box " name="checkBox[]" id="78">Check oil condition and level
     </fieldset> 

     <fieldset class="form-horizontal form-group bg-primary">   
        <input type="checkbox" class="box " name="checkBox[]" id="79">Check coolant condition and level
     </fieldset>

     <fieldset class="form-horizontal form-group bg-primary">   
        <input type="checkbox" class="box " name="checkBox[]" id="80">Check trans fluid condition and level
     </fieldset>

     <fieldset class="form-horizontal form-group bg-primary">   
        <input type="checkbox" class="box " name="checkBox[]" id="81">Check power steering fluid condition and level
     </fieldset>

     <fieldset class="form-horizontal form-group bg-primary">   
        <input type="checkbox" class="box " name="checkBox[]" id="82">Check brake fluid condition and level
     </fieldset>

     <fieldset class="form-horizontal form-group bg-primary">   
        <input type="checkbox" class="box " name="checkBox[]" id="83">Fill washer fluid resevoir
     </fieldset>

     <fieldset class="form-horizontal form-group bg-primary">   
        <input type="checkbox" class="box " name="checkBox[]" id="84">Battery hold down
     </fieldset>

     <fieldset class="form-horizontal form-group bg-primary">   
        <input type="checkbox" class="box " name="checkBox[]" id="85">Check battery &amp; charging system
     </fieldset>

     <fieldset class="form-horizontal form-group bg-primary">   
        <input type="checkbox" class="box " name="checkBox[]" id="86">Inspeect belts
     </fieldset>

and the Jquery I am using unsuccessfully is

$('input[type=checkbox]').on('change', function () {
    $(this).toggleClass('form-horizontal form-group bg-warning',    this.checked);
});




Add checkbox dynamically in java

I wonder how to add checkboxes and name dynamically .

enter image description here

The number of checkboxes is follow the number of row in MySQL and the name is retrieved from MySQL . Assume I have three data in MySQL, so I would get output as image above.

This is my code for class A

checkAPI api= new checkAPI();

try 
{
    num = api.displayCheckBoxAndLabel(); //  get 3
    List<String> allName= api.displayName(); // [John,Tony,Kik]
} 
catch (Exception e1) 
{
    // TODO Auto-generated catch block
    e1.printStackTrace();
                            }    
    deleteAdmin delete = new deleteAdmin(num,allName);
    delete.setVisible(true);
    setVisible(false);
    dispose();
} 

Then pass the two parameters to class deleteAdmin

public class deleteAdmin  extends JFrame {

    private JPanel contentPane;
    private JTextField userText;
    private JTextField txtpassword;
    JFrame f= new JFrame(" Add Admin");

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    button frame = new button();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public deleteAdmin(int num, List<String> names)
    {
        super("Delete Admin");
        setBounds(100, 200, 340, 229);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JPanel panel = new JPanel();
        panel.setBounds(35, 19, 242, 146);
        contentPane.add(panel);
        panel.setLayout(null);

        JCheckBox[] checkBoxList = new JCheckBox[num];

        for(int i = 0; i < num; i++) {
            checkBoxList[i] = new JCheckBox("CheckBox" + i);
            contentPane.add(checkBoxList[i]);
        }
    }
}

However, I get this kind of output. No checkboxes shown :(

enter image description here




how would I pull the data out of the database and re-check the checkboxes that were originally checked and submitted?

I entered checkbox values into the database using the code below. When a user wants to view the checked boxes at a later time, how would I pull the data out of the database and re-check the checkboxes that were originally checked and submitted?

From the code below the data gets entered like this: DATA1|DATA2|DATA3|

var checkbox_value = "";
    $(":checkbox").each(function () {
        var ischecked = $(this).is(":checked");
        if (ischecked) {
            checkbox_value += $(this).val() + "|";
        }
    });

Now how to I take DATA1|DATA2|DATA3| and re-check the corresponding checkboxes?




Copy all checked list item to another list

I trying to realize some features.
When I checked item, it copy to second list.
All work.
I add button, which sets all checkbox as checked. But when I click it, all items dont copy to second list. Can you help me?

<p>First List</p>
<ul class='first-list'>
  <li>
    <input type='checkbox' id='ckbx1'><label for='ckbx1'>One</label>
  </li>
  <li>
    <input type='checkbox' id='ckbx2'><label for='ckbx2'>Two</label>
  </li>
  <li>
    <input type='checkbox' id='ckbx3'><label for='ckbx3'>Tree</label>
  </li>
  <li>
    <input type='checkbox' id='ckbx4'><label for='ckbx4'>Four</label>
  </li>
</ul>
 <span class="addAll">Add All</span>
<p>Second List</p>
<ul class='second-list'>
</ul>

And Jquery

var $chk = $('.first-list input').change(function() {
  $('.second-list').html(
    $chk.filter(':checked').map(function() {
      return $(this).parent().clone();
    }).get()
  );
})
$('.addall').click(function() {
    $('.first-list input').prop('checked',true);
})

Here is fiddle - http://ift.tt/24p79tR

Thanks a lot and sorry for my english.




How to persist a checkall in nested kendo grid in pagination

I have 2 telerik grid,when i search , the parent grid loaded in the screen. when i expand some data, there have list of data. In parent grid have checkbox,when checkall the parentGrid,the child results are selected . pagesize is 20:when go to next page and back to previous page , the checkbox is not gets selected.

case: The problem is when checkall option is working the pagsize in childgrid when checkall in parent grid.

But when select the some row in child grid checkbox and come back to previous its working fine .

    <div ng-show="showGrid">
   <div kendo-grid="gridParent" k-options="gridOptions" id="parentGrid" class="hrScrollOut" k-rebind="gridOptions.selectable" k-data-source="parentDataSource"
             k-on-change="">
        <div k-detail-template>
                <div>
                    <div class="childGrid" id="childGrid" kendo-grid="childGrid" k-options="gridOptionsChild(dataItem)"></div>
                </div>
            </div>
        </div>

In telerik dynamically create the checkbox : 
template: "<input type='checkbox' class='checkbox' />" }

I have given this for child grid ,

> function onDataBound(e) {             var view = this.dataSource.view();
>           for(var i = 0; i < view.length;i++){
>               if(checkedIds[view[i].id]){
>                   this.tbody.find("tr[data-uid='" + view[i].uid + "']")
>                       .addClass("k-state-selected")
>                       .find(".checkbox")
>                       .attr("checked","checked");
>               }           }                   }

can anyone do the example in fiddler:




How to add search and checkbox icon with their functions in android action bar?

I want to add a searchview and checkbox into action bar menu. And this checkbox will be visible if searchview is opened. And in it's opposite case it will be hidden. How I can do this? I do something below . But it doesnt work correctly. I want hide checkbox (In my notes) when searchview is closed. menu.xml

 <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://ift.tt/nIICcg"
        xmlns:app="http://ift.tt/GEGVYd">

        <item
            android:id="@+id/search_button"
            android:icon="@drawable/ic_icon_search"
            android:title="Arama"
            app:showAsAction="ifRoom|collapseActionView"

            app:actionViewClass="android.support.v7.widget.SearchView">

        </item>
        <item
            android:id="@+id/search_in_my_notes_checkbox"
            app:showAsAction="ifRoom"
            android:title="@string/search_in_my_notes"
            android:checkable="true"
            android:visible="false"

            />
    </menu>

HomeActivity.java

 public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == R.id.search_button){
            MenuItem searchInMyNotesCheckbox = (MenuItem)menu.findItem(R.id.search_in_my_notes_checkbox);
            searchInMyNotesCheckbox.setVisible(true);
        }


        return super.onOptionsItemSelected(item);
    }

enter image description here




Android Persistent Checkable Menu in Custom Widget After Reboot Android

Hi I designed a custom toolbar to replace the action bar with a popup menu, using the hints from

how to save menuitem visibility state through sharedpreferences?

and

Checkbox item state on menu android

and

http://ift.tt/1SytdhE

The most effective way is to store the state in shared preferences as in the stackoverflow answers.

My question is: How do I keep the checked option selected even after restarting my android?




Javascript Form Validation - Checkbox from an array, first digit of input

I am having quite a few issues using java script to validate an application form.

  1. validatePostCode: take the value from a selection box and depending on what is chosen, check if the first value of the post code matches the set validation. I tried .charAt(0) but it still displays an error message even if it is correct.

  2. validateTextBox: if the "otherskills" checkbox is checked, the text box cannot be empty. as you can see in my html, my checkbox uses arrays but I don't know to get the value of only "otherskills"

thank you

"use strict"; 
var errMsg = "";
/*get variables from form and check rules*/
function validate(){
var result = true; 

result = validateDOB() && validatePostCode() && validateTextBox() && validateJobReferenceNumber();

if (errMsg != ""){ //only display message box if there is something to show
 alert(errMsg);
 }

return result;
}

function validateDOB(){
var dob = document.forms["regForm"]["dob"].value;
var age = getAge(dob);
var error = document.getElementById("spanDob");
var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
        if (dob == null || dob == "" || !pattern.test(dob) || age < 15 || age > 80) {
        error.textContent = "Please enter a valid date of birth\n";
        return false;
    }
    else {
        return true;
    }
}

function getAge(dob) { /* find age from today's date minus entered DOB*/
    var today = new Date();
    var birthDate = new Date(dob);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

function validatePostCode(){
        var postcode = document.forms["regForm"]["postcode"].value;
        var state = document.forms["regForm"]["state"].value; 
        var error = document.getElementById("spanPostcode");
        switch (state){
                case "VIC":
                if (postcode.charAt(0) !== 3 || postcode.charAt(0) !== 8){
                        error.textContent = "Please enter a valid post code for VIC";
                        return false;
                }
                break;
                case "NSW":
                if (postcode.charAt(0) !== 1 || postcode.charAt(0) !== 2){
                        error.textContent = "Please enter a valid post code for NSW"
                        return false;
                }
                break;
                case "QLD":
                if (postcode.charAt(0) !== 4 || postcode.charAt(0) !== 9){
                        error.textContent = "Please enter a valid post code for QLD"
                        return false;
                }
                break;
                case "NT":
                if (postcode.charAt(0) !== 0){
                        error.textContent = "Please enter a valid post code for NT"
                        return false;
                }
                break;
                case "WA":
                if (postcode.charAt(0) !== 6){
                        error.textContent = "Please enter a valid post code for WA"
                        return false;
                }
                break;
                case "SA":
                if (postcode.charAt(0) !== 5){
                        error.textContent = "Please enter a valid post code for SA"
                        return false;
                }
                break;
                case "TAS":
                if (postcode.charAt(0) !== 7){
                        error.textContent = "Please enter a valid post code for TAS"
                        return false;
                }
                break;
                case "ACT":
                if (postcode.charAt(0) !== 0) {
                        error.textContent = "Please enter a valid post code for ACT"
                        return false;
                }
                break;
                default: 
                error.textContent = "Please enter a valid post code";
                return false;
        }
        return true;
}

function validateTextBox(){
        var checkboxOtherSkills = document.getElementById("skills[]").getElementsByTagName("input"); 
        var textbox = document.forms["regForm"]["otherSkills"].value;

        if (checkboxOtherSkills[oSkills].checked){
                if (textbox.length < 1){
                        errMsg +="'Other Skills' has been selected but not filled out.";
                        return false;
                }
        } 
        return true;
}

function validateJobReferenceNumber(){
        var refnumb = document.getElementById("jobrefno");
        var pattern = (/([a-zA-Z0-9_-]){6}$/);

        if (!pattern.test(refnumb)){
                errMsg += "6 alphanumeric characters only";
                return false;
        }
        return true;
}

function init(){
        var regForm = document.getElementById("regForm");// get ref to the HTML element
        regForm.onsubmit = validate; 
}

window.onload = init;
<form id="regForm" method="post" action="http://ift.tt/1rGQD7h" novalidate="novalidate">
        <fieldset><legend>Application:</legend>

        <!--Job Reference Number-->
        <p><label for="jobrefno">Job Reference Number</label>
        <input type="text" name="jobrefno" id="jobrefno" pattern="[a-zA-Z0-9]{6}" title="Must be 6 characters" required="required" /><span id="spanJobRefNo"></span></p>
        <!--First Name-->
        <p><label for="firstName">First Name</label>
        <input type="text" name="firstName" id="firstName" pattern="[a-zA-Z]+${1,25}" maxlength="25" title="Max Length 25" required="required" /><span id="spanFirstName"></span></p>
        <!--Last Name-->
        <p><label for="lastName">Last Name</label>
        <input type="text" name="lastName" id="lastName" pattern="[a-zA-Z ]+${1,25}" maxlength="25" title="Max Length 25" required="required" /><span id="spanLastName"></span></p>
        <!--Date of Birth-->
                <p><label for="dob">Date of Birth</label>
        <input type="text" name="dob" id="dob" required="required" placeholder="dd/mm/yyyy"/><span id="spanDob"></span></p>
        <!--Gender-->
        <fieldset><legend>Gender</legend></span>
        <p><label>  <input type="radio" name="gender" value="Unspecified" checked="checked"/>Prefer not to say</label>
        <label><input type="radio" name="gender" value="Female" />Female</label>
        <label><input type="radio" name="gender" value="Male" />Male</label></p>
        <span id="spanGender"></fieldset>   
        <!--Street Address-->
        <p><label for="streetAddress">Street Address</label>
        <input type="text" name="streetAddress" id="streetAddress" maxlength="40" title="Max Length 40" required="required" /><span id="spanStreetAddress"></span></p>
        <!--Suburb-->
        <p><label for="suburb">Suburb</label>
        <input type="text" name="suburb" id="suburb" maxlength="40" title="Max Length 40" required="required" /><span id="spanSuburb"></span></p>
        <!--State-->      
        <p><label for="state">State</label>
        <select required ="required" name="state" id="state">
        <option value="" selected="selected">Please Select</option>
        <option value="VIC">VIC</option>
        <option value="NSW">NSW</option>
        <option value="QLD">QLD</option>
        <option value="NT">NT</option>
        <option value="WA">WA</option>
        <option value="SA">SA</option>
        <option value="TAS">TAS</option>
        <option value="ACT">ACT</option>
        </select>
        <span id="spanState"></span>
        </p>
        <!--Postcode-->
        <p><label for="postcode">PostCode</label>
        <input type="text" name="postcode" id="postcode" pattern="[0-9]{4}" maxlength="4" title="4 Digits only" required="required" /><span id="spanPostcode"></span>
        <!--Email address-->
        <p><label for="email">Email</label>
        <input type="email" name="email" id="email" placeholder="youremail@host.com" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" title="Please use correct format: eg. mrburns@hotmail.com" required="required" /><span id="spanEmail"></span></p>
        <!--Phone Number-->
        <p><label for="phoneNumber">Phone Number</label>
        <input type="text" name="phoneNumber" id="phoneNumber" pattern="[0-9]+{8,12}" maxlength = "12" title="8-12 Digits" required="required" /><span id="spanPhoneNumber"></span>           
        </p>
        <!--Skill List-->
        <label>Skills List</label><br>
        <label><input type="checkbox" name="skills[]" value="HTML5" checked="checked" />HTML5</label><br>
        <label><input type="checkbox" name="skills[]" value="CSS" />CSS</label><br>
        <label><input type="checkbox" name="skills[]" value="JavaScript">JavaScript</label><br>
        <label><input type="checkbox" name="skills[]" value="Excel" />Excel</label><br>
        <label><input type="checkbox" name="skills[]" value="MySQL" />MySQL</label><br>
        <label><input type="checkbox" name="skills[]" value="Administration" />Administration</label><br>
        <label><input type="checkbox" name="skills[]" value="12MoExp" />12 Months Experience</label><br>
        <label><input type="checkbox" name="skills[]" id ="oSkills" value="OtherSkills" />Other Skills...</label><br>
        <!--Other Skills-->
        <p><label for="otherSkills">Other Skills</label> <span id="spanOtherSkills"></span><br>
        <textarea id="otherSkills" name="otherSkills" rows="10" cols="50" placeholder="Please tell us about any other skills you have that may benefit you in this position"></textarea></p>
        </fieldset>
        <p>
        <input type= "submit" value="Apply"/>
        <input type= "reset" value="Reset Form"/></p>
</form>



Uncheck and Check checkbox in a switch case

When a checkbox will be checked or unchecked, I want the icon to appear or dissappear. Below I am showing how the icon url path looks. Is there any way I can do that? I've been trying myself to add this code to the switch case, but I'm a beginner with js & jquery and I don't know what Im doing wrong.

$('#someId').change(function()  {

        if(this.checked)    {
            $(icon = greenIcon).show(1);
        }
        else    {
            $(icon = greenIcon).hide(1);
        }

    });

    $('#someId2').click(function()  {

        if(this.checked)    {
            $(icon = yellowIcon).show(1);
        }
        else    {
            $(icon = yellowIcon).hide(1);
        }

    });

    $('#someId3').click(function()  {

        if(this.checked)    {
            $(icon = redIcon).show(1);
        }
        else    {
            $(icon = redIcon).hide(1);
        }

    });

    $('#someId4').click(function()  {

        if(this.checked)    {
            $(icon = blueIcon).show(1);
        }
        else    {
            $(icon = blueIcon).hide(1);
        }

    });

into this

switch (feature.properties.status) {
        case 0:   
            icon = greenIcon; break;
        case 1:
        case 11:
        case 12:
            icon = yellowIcon; break;
        case 2: 
        case 21:    
        case 22:    
            icon = redIcon; break;
        case 5: 
        default:
            icon = blueIcon; break;
}

Icons are added to the code like this:

var greenIcon = new LeafIcon({iconUrl: L.Icon.Default.imagePath + 'marker-icon-ok.png'});
var redIcon = new LeafIcon({iconUrl: L.Icon.Default.imagePath + 'marker-icon-err.png'});
var yellowIcon = new LeafIcon({iconUrl: L.Icon.Default.imagePath + 'marker-icon-warn.png'});
var blueIcon = new LeafIcon({iconUrl: L.Icon.Default.imagePath + 'marker-icon-sleep.png'});

So when a checkbox is checked or unchecked, the icon would appear or dissappear. Is it possible?




POST checked and unchecked checkboxes with html php

Im having hard time to figure it out how to insert the checked box-es or unchecked into the database with php.

I tried many many different ways but none is working, i think im very close but can't figure it out the problem. Btw i work with javascript and never worked with php except this time.

index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://ift.tt/nYkKzf">
<head>
   <style type="text/css">
      @import "demo_page.css";
      @import "header.ccss";
      @import "demo_table.css";
      @import "select.dataTables.min.css";
      @import "jquery.dataTables.min.css";
   </style>
   <script src="http://ift.tt/1oMJErh"></script>
   <script type="text/javascript" charset="utf-8" src="jquery.js"></script>
   <script type="text/javascript" charset="utf-8" src="jquery.dataTables.js"></script>
   <script type="text/javascript" charset="utf-8" src="RowGroupingWithFixedColumn.js"></script>
   <script>$(document).ready(function(){load_(); console.log('load running')});</script>
</head>
</head>
<body id="dt_example">
   <table cellpadding="0" cellspacing="0" border="0" class="display" id="endpoints">
   <thead>
      <tr>
         <th></th>
         <th>Nr.</th>
         <th>Java Class Name</th>
         <th>http Method</th>
         <th>URL</th>
      </tr>
   </thead>
   <tbody>
      <?php
         $con = mysqli_connect('sql7.freemysqlhosting.net','sql7117068','GZqaZj69G9','sql7117068');
         if (!$con) {
             die('Could not connect: ' . mysqli_error($con));
         }
         mysqli_select_db($con,sql7117068);
         $sql='SELECT * FROM url';
         $result = mysqli_query($con,$sql);
         $checkboxes = $_GET['case'];
         
         echo "<script>console.log(" . $checkboxes.length . ");</script>";
         
         
         
         while($row = mysqli_fetch_array($result)) {
           print $row['method'];
           switch ($row['http_method']) {
                         case "GET":
                             echo "<tr class='gradeA'>";
                             break;
                         case "PUT":
                               echo "<tr class='gradeC'>";
                             break;
                         case "POST":
                               echo "<tr class='gradeU'>";
                             break;
                         case "DELETE":
                               echo "<tr class='gradeX'>";
                             break;
                         default:
                               echo "<tr>";
                     }
           if($row['checked']){
             echo "<td><input type='checkbox' id=case name='case[]' value='" . $row['number']  . "' checked> </td>";
           } else {
             echo "<td><input type='checkbox' id=case name='case[]' value='" . $row['number']  . "'> </td>";
         
           }
             echo "<td align=center >" . $row['number'] . "</td>";
             echo "<td align=center >" . $row['class_name'] . "</td>";
             echo "<td>" . $row['http_method'] . "</td>";
             echo "<td style='font-weight:bold'>" . $row['endpoint']  . "</td>";
             echo "</tr>";
         
         }
         
         if(!empty($_POST['case'])){
           foreach($_POST['case'] as $case){
                  $sql= "UPDATE url SET checked = 1 WHERE number = " . $case;
                  $result = mysqli_query($con,$sql);
            }
         }
         
         mysqli_close($con);
         echo "</tbody></table>";
         
         echo "<input type=submit name=submit id='save' value=Save>";
         include 'save.php';
         ?>
</body>
</html>

Also this code works very well to get the datas from the databse in one free host, but it doesnt work for saving.

Also separate php file i tryed but without success. save.php

  if(isset($_POST['submit'])){
  if(!empty($_POST['check_list'])) {

    $con = mysqli_connect('sql7.freemysqlhosting.net','sql7117068','GZqaZj69G9','sql7117068');
    if (!$con) {
       die('Could not connect: ' . mysqli_error($con));
    }
    mysqli_select_db($con, 'sql7117068');
    $checkbox = $_GET['case'];

      echo "<script>console.log(" . $checkboxes.length . ");</script>";

    foreach($_POST['case'] as $case){
          $sql = "UPDATE url SET checked = 1 WHERE number = " . $case;
          $result = mysqli_query($con,$sql);
        }
     }
      mysqli_close($con);
    }

?>

checkboxes




I am unable to retrieve values of selected checkboxes in angularjs

can anybody tell me how should I retrieve values of selected checkboxes in angularjs. I will give you a brief scenario. I have an object called 'user' in which I have a list of permissions as a member of 'user'. Now in jsp I have several check boxes, what I want is when I check checkboxes the values of selected checkboxes should be mapped with permission list whoch is present in the 'user', How can I do that.? I will show my permission checkboxes jsp code which is as follows

<div class="form-group required">
                                                                <label for="Permissions" class="col-sm-3 control-label">Permissions</label>
                                                                <div class="col-sm-6 Nopadding" data-ng-model="ctrl.user.permissionVoList.permissionId">
                                                                    <div class="checkbox"   data-ng-repeat="permissionVo in ctrl.permissionVoList" >
                                                                        <label data-toggle="tooltip" data-placement="right"
                                                                            data-html="true"
                                                                            title="<p align='left'></p>">
                                                                            <input type="checkbox" value= /> 
                                                                        </label>
                                                                    </div>

                                                                </div>
                                                            </div>

and 'user' object in the controller is as follows

 self.user={
                  userId:'1',
                  firstName:'Vishal',
                  middleName:'Vasant',
                  lastName:'Raut',
                  phoneNumber:'9898989898',
                  emailId:'vishal@gmail.com',
                  username:'vishal',
                  password:'111111',
                  notification:'no',
                  costPerHour:'1000',
                  roleVo:{roleId:''},
                  shiftVo:{shiftId:''},
                  permissionVoList:[{permissionId:''}]

            };




Toggling dynamically created checkbox in react

I have created a table dynamically in react with some fields and a checkbox in each row. Now In the column header I have a checkbox. When I click the checkbox I want all the rows checkbox to be selected. Also now if I click any checkbox, that should toggle its state.

Till now I am able to generate the dynamic rows in the table and delete individual rows.

Table Headers

                           <div class="row">
                                <div class="col-md-12">
                                    <div class="table-responsive">  
                                        <table id="mytable" class="table table-bordred table-striped">  
                                            <thead>  
                                                <th><input type="checkbox" id="checkall" onChange={this.checkAll}/></th>
                                                <th>Id</th>
                                                <th>Id1</th>
                                                <th>Id2</th>
                                                <th>Email</th>
                                                <th>Edit</th>  
                                                <th>Delete</th>
                                            </thead>
                                            <tbody>{users}</tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

Function to add new user

addUserState =(dat) => {
        let data = JSON.parse(dat);
        let id = this.randomPassword(32);

        let newElement = null
        newElement = <tr>
                    <td><input type="checkbox" class="checkthis"/></td>
                    <td class="userId">{id}</td>
                    <td class="id1">{data.payload.id1}</td>
                    <td class="id2">{data.payload.id2}</td>
                    <td class="userEmail">{data.payload.email}</td>
                    <td><p data-placement="top" title="Edit"><button class="btn btn-primary btn-xs" data-title="Edit" ><span class="glyphicon glyphicon-pencil"></span></button></p></td>
                    <td><p data-placement="top" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" onClick={this.deleteUser.bind(this, id)}><span class="glyphicon glyphicon-trash"></span></button></p></td>
                    </tr>
        this.setState({users: this.state.users.concat([newElement])});
    }

CheckAllfunction:

checkAll = (e) => {
        let length = this.state.users.length;
        if(e.target.checked) {
            for(let i = 0; i < length; i++) {
                console.log(this.state.users[i]);
                //Do what here
            }
        }

    }

one possible way I find is to associate a checked state property with each of the checkboxes that I create but it will be difficult to manage, since I will be performing CRUD operations on the rows.

Thanks for help in advance




Checkbox is unchecked but the content of a checked checkbox is showing up

Just like the title says. Here is my code:

$('#somediv').change(function() {
    if(this.checked) {
        $('.leaflet-marker-pane').show(1);
    }
    else {
        $('.leaflet-marker-pane').hide(1);
    }       
});

<input style="float: left;" type="checkbox" id="somediv" name="somediv">

This happens when the browser is refreshed. The content should not show up, because the checkbox is unchecked, but it is showing up.




Getting data from a specific column in a HTML table when a checkbox in that row is checked using Javascript/JQuery

I have a HTML table with 5 columns. The first column is a checkbox. I want to find the content of the 5th column (last column) when the checkbox in that row is checked.

HTML :

    <table>
     <tr>
      <th></th>
      <th>A</tr>
      <th>B</tr>
      <th>C</tr>
      <th>D</tr>
     </tr>
     <tr>
      <td><input type='checkbox' class="chk" /></td>
      <td>data for A1</td>
      <td>data for B1</td>
      <td>data for C1</td>
      <td>data for D1</td>
     </tr>
     <tr>
      <td><input type='checkbox' class="chk"/></td>
      <td>data for A2</td>
      <td>data for B2</td>
      <td>data for C2</td>
      <td>data for D2</td>
     </tr>
    </table>

I am a beginner in javascript but have tried doing this.

**JS : **

    $(document).ready(function(){
      if($('input.chk').is(':checked')){
         var y = $("td:nth-of-type(5)").html();
         alert(y);
         }
      });

This function returns only for the first row i.e when the checkbox is checked it shows "data for D1". But I want it for all the rows.

Thanks for your help. :)




Checkboxes in listbox not getting checked via binding

I'm trying to check all the checkboxes through a binding. The getChecked property does get changed to true after clicking the button but the checkboxes are just not getting checked. Does someone see what I'm doing wrong here? This is the XAML code for the listbox.

<ListBox Name="scroll"  ItemContainerStyle ="{StaticResource _ListBoxItemStyle}" Tag="{Binding SortingIndex}"  BorderBrush="#C62828" BorderThickness="1" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Name="checkboxStack">
                        <CheckBox IsChecked="{Binding Path=getChecked}"  Content="{Binding Path=vraag}"  Style="{StaticResource LifesaversCheckBoxesA}"/>
                        <StackPanel Margin="20,0,0,0">
                            <RadioButton GroupName="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=Tag}" Content="{Binding Path=antwoorden[0]}" FontSize="15" />
                            <RadioButton GroupName="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=Tag}" Content="{Binding Path=antwoorden[1]}" FontSize="15" />
                            <RadioButton GroupName="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=Tag}" Content="{Binding Path=antwoorden[2]}" FontSize="15" />
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

This is the event handler for the button I made to change the getChecked boolean to true for each vraag in vragenLijst. The sample data is just to generate some random strings.

public partial class LivesaversWindow : UserControl
{
    ObservableCollection<Vraag> vragenLijst;
    public LivesaversWindow()
    {
        InitializeComponent();
        vragenLijst = new VragenList(SampleData.vragen());

        scroll.ItemsSource = vragenLijst;

    }

    private void alles_Selecteren(object sender, RoutedEventArgs e)
    {
        if ((string)select.Content == "Alles selecteren")
        {
            foreach(Vraag vraag in vragenLijst)
            {
                vraag.getChecked = true;

            }
            select.Content = "Alles deselecteren";
        }
        else
        {
            foreach (Vraag vraag in vragenLijst)
            {
                    vraag.getChecked = false;
            }
            select.Content = "Alles selecteren";
        }
    }

And these are the 2 classes I'm using.

    public class Vraag 
{
    public List<string> antwoorden { get; set; }
    public string vraag { get; set; }
    public Boolean getChecked { get; set; }
}





 public class VragenList : ObservableCollection<Vraag>
{
    public VragenList(List<Vraag> vragen) :base()
    {
        foreach (var vraag in vragen)
        {
            Add(vraag);
        }
    }
}




how to fill a combobox in a userform using vlookup of the values inserted in other comboboxes?

I have a table where I have for each month the type of shrimp and quantity caught and also the weight of each type of shrimp. In the first column of this table, I'm concatenating the shrimptype and the quantity.

So using a userform, I want that once the user chooses the shrimp type from a combobox list "shrimptype"(cbshrimptype) and quantity "700" in a textbox (tbquantity),

I want that the combobox of the shrimp weight takes the value that corresponds to shrimptype700 already concatenated in the table described above, and that exists in the 7th column of the table. (chshrimptype is a checkbox) That's the code that I tried and that didn't work:

If chshrimptype.Value = True Then Me.cbshrimpweight.Text = Application.WorksheetFunction.VLookup((Me.cbshrimptype.Text & Me.tbquantity.Text), Worksheets("Table").Range("shrimp"), 7, False) End If

Thank you so much for your help !




Item from one list to another based on the checkbox value

all. I have some problem and I have no idea how solve it. I have two list. In first - items with checkbox and label

<p>First List</p>
<ul class='first-list'>
  <li>
    <input type='checkbox' id='ckbx1'><label for='ckbx1'>One</label>
  </li>
  <li>
    <input type='checkbox' id='ckbx2'><label for='ckbx2'>Two</label>
  </li>
  <li>
    <input type='checkbox' id='ckbx3'><label for='ckbx3'>Tree</label>
  </li>
  <li>
    <input type='checkbox' id='ckbx4'><label for='ckbx4'>Four</label>
  </li>
</ul>
<p>Second List</p>
<ul class='second-list'>
<ul>

I need: When I checked item, it copy to second list. When unchecked - this item should be removed from second list. Here basic structure - http://ift.tt/1VWnN39

PS. Sorry for my English




jeudi 28 avril 2016

Ionic/AngularJS checkbox and ng-repeat from API

The idea was to send true checkbox values from mobile to API so I can place an order with selected condiments, however I cant to get a grasp on it. Condiments are returned from HTTP GET call to API.

<ion-checkbox ng-repeat="condiment in condiments" ng-model="condiment.checked"
                          ng-checked="checkItem(condiment.id)">
                
                
</ion-checkbox>

It calls the function:

$scope.checkItem = function (id) {
            return $scope.condiments[id-1].checked = true;
};

(minus 1 is because ID starts at 1, and array at 0) But it is not called when checked/unchecked, but rather it makes all my resources checked by default, and once I click to uncheck them, nothing changes.

Property 'checked' is not part of the original JSON API output for the condiment. It has ID, name and price.

Question:

Is there a less painful way to send checked ID's back to server?

Edit:

I tried to set the default variables before, but that does nothing:

for(var i=0; i<$scope.condiments; i++){
            $scope.condiments[i].checked = false;
}




Store checked checkbox in gridview in database ASP.NET C#

I am able to retrieve out data from database to show which is Y and N using checkbox in gridview. However now i want to to able to store which checkbox is checked back into the database after editing.

What i did so far:

.aspx

 <asp:GridView ID="SiteGridView" runat="server" CssClass="datagrid" 
                        GridLines="Vertical" AutoGenerateColumns="False" Width="100%" 
                        AllowPaging="True" AllowSorting="True" 
                        DataKeyNames="promoID"  OnRowCommand="GvPage_RowCommand" 
                        OnPageIndexChanging="GvPage_PageIndexChanging" 
                        OnSorting="GvPage_Sorting" 
                        onrowdatabound="SiteGridView_RowDataBound" OnRowEditing="SiteGridView_RowEditing">
                        <Columns>       
   <asp:TemplateField HeaderText="Default">
                                <ItemTemplate>
                                    <asp:CheckBox ID="process_flag" runat="server" Checked='<%# bool.Parse(Eval("PROCESSED").ToString()) %>' Enable='<%# !bool.Parse(Eval("PROCESSED").ToString()) %>' />
                                  </ItemTemplate>
                                 <ItemStyle Width="20%" />
                            </asp:TemplateField>
   </Columns>
                </asp:GridView>

CodeBehind:

 SqlCommand cmd = new SqlCommand("SELECT * , CAST(CASE defaults WHEN 'Y' THEN 1 ELSE 0 END AS BIT) AS PROCESSED FROM Promotions"); 
            SqlDataAdapter da = new SqlDataAdapter(); 
            DataTable dt = new DataTable(); 
            da.SelectCommand = cmd; 

            // Save results of select statement into a datatable 
            da.Fill(dt);

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




Checkbox states change after navigating to another page

I am trying to persist the checkbox states after user traverse to another page on my rails web site.

Currently, when i navigate from index page to another page and come back to the index page checkboxes from index page get checked. I want it to hold the values I give even if I navigate to another page.

I have written

function addingChecks() {
    var filterStatusArr = [];
    filterStatusArr = localStorage.filterStatus;
    $('#filterText h4 .onoffswitch .onoffswitch-checkbox').each(function() {
        for (var i = 0; i < filterStatusArr.length; ++i) {
            if (filterStatusArr[i] == "true") {
                $(this).prop('checked', true);
            } else {
                $(this).prop('checked', false);
            }
        }
    });
};

rememberFilterState();
addingChecks();
function rememberFilterState() {

    filterStatus = [];
    $('#filterText h4 .onoffswitch .onoffswitch-checkbox').each(function() {
        if ($(this).is(':checked')) {
            filterStatus.push("true");
        } else {
            filterStatus.push("false");
        }
        localStorage.input = filterStatus;
    });
    //alert(filterStatus);
}

Works well onload but this ignores when I go to another page and come back.

Is this the approved behavior? How can I fix this?

Cheers




Creating checkboxes dynamically using Google App Script for a Web App

I have been able to produce a 2D Array where its elements are cells from a Google Sheet in Google Scripts. I want to display these as checkboxes in a Web app. However I cannot work out how to add these elements as checkboxes. From what I can understand the getElementById() function doesn't work so I can't add checkboxes through Google Script like I would in normal JS. I call this function through an onClick action in my HTML and the form element "equipForm" is not populated with anything...Below is a code I have attempted to use.

function populateEquipmentBoxes1(){
var equipment = getEquipmentArray(); //generates a 2D array
var outputDiv = document.getElementById("equipForm");

   for(var i=0; i<equipment.length;i++){
     for(var j=1;j<equipment[i].length;j++){
        equipment[i] = equipment[i].filter(function(n){ return n != "" });
        Logger.log(equipment[i][j]);
        var check = document.createElement("input");
        check.type = 'checkbox';
        check.id = equipment[i][1]+j; // need unique Ids!
        check.value = equipment[i][j];

        var label = document.createElement('label')
        label.htmlFor = equipment[i][j];
        label.appendChild(document.createTextNode('text for label after checkbox'));
        outputDiv.appendChild(check);
        outputDiv.appendChild(label);
     }
   }

}

I completely realise it is 99% due to a lack of understanding, however I don't really know how else to do what I am trying to do, any help or resources would be great!

Thanks!




How to retrieve values of a checked checkbox in datatables pagination using javascript?

I have been using datatables for my project and only I discovered recently that the javascript I used is only selecting the checkboxes in the current page. Values of checked checkbox in other pagination/page is not selected or retrieved. Is there a way I can recognize checked checkboxes in all page of a pagination? Please help. Here is my code.

$('#create-po').click(function(e){     
    e.preventDefault();

     $("input:checkbox:checked").each(function(i){
       valArray[i] = $(this).val();
     });

 });

This code recognizes checked checkboxes in a current page but not recognizes checked checkboxes in other page.




java - change to check boxes

I am creating a pizza ordering system that when it runs u have to select the size from a scroll bar and then the toppings from a scroll bar. then once order is pressed. what is ordered will appear in order summary. I never use check boxes so I have no idea how to replace the stroller for toppings for check boxes. Can someone please help me. I need this done. The reason I need to is so I can select multiple values and then deselect when I click again. Thank you

here is my code:

package lab;

    import javafx.application.Application;
    import javafx.collections.*;
    import javafx.event.*;
    import javafx.geometry.Pos;
    import javafx.stage.Stage;
    import javafx.scene.layout.*;
    import javafx.scene.paint.Color;
    import javafx.scene.control.*;
    import javafx.scene.Scene;
    import javafx.scene.shape.*;
    import javafx.scene.paint.*;

    public class pizza extends Application{
        private ComboBox<String> size;
        private ListView<String> toppings;
        private TextField order;
        private Button orderit, clearit;
        private Label lb_flavor, lb_tops, lb_order;
        private ObservableList<String> flavor =
                FXCollections.observableArrayList (
                        "Small", "Medium",
                        "Large", "extra Large");
        private ObservableList<String> tps =
                FXCollections.observableArrayList(
                        "pineapples", "pepperoni",
                        "peppers", "bacon", "sausage",
                        "ham");
        public void start(Stage primaryStage) {
            // areas to place the various components
            VBox pane = new VBox(15);
            HBox flavor_pane = new HBox(10);
            HBox topping_pane = new HBox(10);
            HBox order_pane = new HBox(10);

            lb_flavor = new Label("Sizes");
            size = new ComboBox(flavor);
            size.setVisibleRowCount(4);
            size.setValue(flavor.get(0)); // display the first one

            flavor_pane.getChildren().addAll(lb_flavor, size);

            lb_tops = new Label("toppings");
            toppings = new ListView(tps);
            toppings.setPrefSize(100,80);
    toppings.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);


            topping_pane.getChildren().addAll(lb_tops, toppings);

            lb_order = new Label("Order Summary");
            order = new TextField();
            order.setEditable(false);
            order.setPrefColumnCount(25);

            order_pane.getChildren().addAll(lb_order, order);

            orderit = new Button("Place Order");
            clearit = new Button("Clear Order");

            // Subscribe for when the user clicks the buttons
            OrderHandler oh = new OrderHandler();
            orderit.setOnAction(oh);
            clearit.setOnAction(oh);

            pane.getChildren().addAll(flavor_pane,
                    topping_pane, order_pane, orderit, clearit);

            Scene scene = new Scene(pane, 400, 300);
            primaryStage.setTitle("pizza ordering");
            primaryStage.setScene(scene);
            primaryStage.show();

        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Application.launch(args);
        }
    class OrderHandler implements EventHandler<ActionEvent>{
        public void handle(ActionEvent e) {
            // was it the clear button  
            if (e.getSource() == clearit) {
                order.setText("");
                toppings.getSelectionModel().clearSelection();
                size.setValue(flavor.get(0));
                return;
            }
            // flavor
            String result = size.getValue();
            // for toppings
            ObservableList<String> selections =
            toppings.getSelectionModel().getSelectedItems();
            // convert to an array
            Object[] objs = selections.toArray();
            for (int k =0 ; k < objs.length; k++){
                result += " " + objs[k].toString();
            }
            order.setText(result);
        }
    }
    }




JavaScript - uncheck radio button if no checkboxes are checked

I already asked a different question here: JavaScript - Select radio button if any checkbox is checked

I had another question so I am creating a new question for this. I was told to do the same. Hence, the new question. Hope it's alright.

I'm able to populate the radio button Radio 1 if any PD checkbox in Groups 1 and 2 are checked. Similarly, I'm also able to populate the radio button Radio 2 if any ID checkbox in Groups 1 and 2 are checked.

Following is the HTML:

<form>
   <h3>Radio Buttons</h3>
   <input type="radio" name="radio1" id="radio1"> Radio 1
   <br>
   <input type="radio" name="radio2" id="radio2">Radio 2
   <br>
   <br>

   <h3>Checkbox Groups</h3>

   <h4><u>Group 1</u></h4>
   <p align="center"><u>PD</u></p>
   <ul>
      <li>
          <input class="pdcb" type="checkbox" name="G1PD1" onclick="validate()">G1 PD1</li>
      <li>
         <input class="pdcb" type="checkbox" name="G1PD2" onclick="validate()">G1 PD2</li>
   </ul>
   <p align="center"><u>ID</u></p>
   <ul>
      <li>
         <input class="idcb" type="checkbox" name="G1ID1" onclick="validate()">G1 ID1</li>
      <li>
         <input class="idcb" type="checkbox" name="G1ID2" onclick="validate()">G1 ID2</li>
   </ul>

   <h4><u>Group 2</u></h4>
   <p align="center"><u>PD</u></p>
   <ul>
      <li>
     <input class="pdcb" type="checkbox" name="G2PD1" onclick="validate()">G2 PD1</li>
      <li>
         <input class="pdcb" type="checkbox" name="G2PD2" onclick="validate()">G2 PD2</li>
   </ul>
   <p align="center"><u>ID</u></p>
   <ul>
       <li>
          <input class="idcb" type="checkbox" name="G2ID1" onclick="validate()">G2 ID1</li>
      <li>
          <input class="idcb" type="checkbox" name="G2ID2" onclick="validate()">G2 ID2</li>
   </ul>
</form>

Following is the JS code:

function validate()
{
var pdcbClass = document.getElementsByClassName("pdcb");
var idcbClass = document.getElementsByClassName("idcb");
console.log(this);

for (var i = 0; i < pdcbClass.length; i++) 
{
    if (pdcbClass[i].checked == true) 
    {
        document.getElementById("radio1").checked = true;
        document.getElementById("radio2").checked = false;
    }
}

for (var i = 0; i < idcbClass.length; i++) 
{
    if (idcbClass[i].checked == true) 
    {
        document.getElementById("radio1").checked = false;
        document.getElementById("radio2").checked = true;
    }
}

var pdcbClass2 = document.getElementsByClassName("pdcb");
var idcbClass2 = document.getElementsByClassName("idcb");
console.log(this);

//if none of the checkboxes are checked, don't populate radio buttons
for (var i = 0; i < pdcbClass2.length; i++) 
{
    if (pdcbClass2[i].checked == false) 
    {
        document.getElementById("radio1").checked = false;
        document.getElementById("radio2").checked = false;
    }
}

for (var i = 0; i < idcbClass2.length; i++) 
{
    if (idcbClass2[i].checked == false) 
    {
        document.getElementById("radio1").checked = false;
        document.getElementById("radio2").checked = false;
    }
}
}

Now, my question is how would I get the radio buttons to not get populated if none of the checkboxes are checked?

PS: I need to write this in pure JavaScript. I cannot use jQuery.




spring form checkbox id creation fails

I was trying an example which shows list of books with checkbox for each book. by using

<form:checkboxes items="${book.allBooks}"  path="selectedBooks"/>

</form:form>

Here book object is backing object. Here if I see view source of my JSP, it shows the id for each checkbox as selectedBooks1, selectedBooks2 etc. But I want the ID be like --

When I tried to include ID attribute for form:checkboxes as id="chk_${book.allBooks.isbn}" getting exception pasted below.

NOTE: I have getter and setter for isbn paramater in my Book class and it is of type int. Any help is appreciated. thanks

it throws exception as

root cause:

java.lang.NumberFormatException: For input string: "isbn"
java.lang.NumberFormatException.forInputString(Unknown Source)




how to restrict the uncheck of last checkbox using angular js?

i have a list containing checkboxes i want to specify a condition where user can select maximum 5 checkboxes if he tries to select the 6th box a popup should be shown as max count reached , similarly one checkbox should always be selected when user tries to deselect the only left checkbox again their should be a popup than min count reached .

my html :

<div ng-show="isFilterOpen" class="filterDiv1">
            <div class="filterTitle">Select any 5 from the list <br> Currently Selected.</div>
            <div class="checkValue">
                <ion-checkbox ng-repeat="item in unfilteredLabel" ng-model="item.value" ng-checked="item.value" ng-disabled="(clicked && !item.value)" ng-change="selectField(item.label,item.value)">
                    
                </ion-checkbox>
            </div>
            <br>
            <div class="solidLine"></div>
            <br>
            <button class="done" ng-click="callRePaint()">Done</button>
        </div>

my controller code:

$scope.selectField = function(label , value) {
            count = 0;
            for (i = 0; i < $scope.unfilteredLabel.length; i++) {
                if($scope.unfilteredLabel[i].label == label){
                    //$scope.unfilteredLabel[i].value = false;
                }

                if ($scope.unfilteredLabel[i].value) {

                    count++; //count variable contains the number of fields selected
                    console.log(count);

                }

            }
            $scope.filterRemCount=count;
            if (count > (isSmallScreen?1:4)){
                $scope.clicked = true;
                //alert("cannot select more than 5");
            } else {
                $scope.clicked = false;
            }   

             CreatorTableRecord.setcheckedvalue($scope.unfilteredLabel);
            FullTableRecord.setcheckedvalue($scope.unfilteredLabel);

        }

how should i specify the condition to show the popup when count reaches max or min and when count shows min value the last checkbox should be restricted for deselection after showing the popup




Multiple checkboxes to toggle related div

I've tried to look around other very similar questions but none seem to have a solution.

How would I go about achieving the following scenario:

Layout:

Checkbox 1 "Orange"  
Checkbox 2 "Apple"  
Checkbox 3 "Banana"  

Div 1 "Orange"  
Div 2 "Apple"  
Div 3 "Banana"  

When you load the page, all you can see is the checkboxes. When the user selects a checkbox, the corresponding div is displayed. If the user then selects another checkbox, the original div is hidden and the newly selected one is displayed.

I can only use a checkbox as it's for another purpose whereby checkbox is the desired option.

My code so far:

$(document).ready(function() {
    $('.toggle input[type="checkbox"]').on('change', function() {
        $('input[type="checkbox"]').not(this).prop('checked', false).change();
        var name = $(this).attr('name');
        if ($(this).attr("type") === "checkbox") {
            $(this).parent().siblings().removeClass("selected");
            $("#" + name).toggle(this.checked);
        }
        $(this).parent().toggleClass("selected");
    });
});




Binding an unique value from a table to ng-model of a check box

I have a table(which is populated with the data that is received from back end using ng-repeat.)Each of the rows have a check box and if the check box is selected(multiple) i want to send a request to the server to delete the rows.To do this i want to bind my check box to an unique field in my table but am unable to get the right syntax. i tried the below options that i read in SO but nothing seems to work.

  <input type="checkbox" ng-model="demo.Custid" >//this replaced the value in the table with true or false.

  <input type="checkbox" ng-model="formData.checkboxes[demo.Custid]" >//this gave me values in the below  format {"12500":true,"125001":false}

Is there anyway i can get the value of the customer id(in this case)directly bound to the ng-model uniquely?I want to get these values and send a request to the server to delete the data from the table for the corresponding customer.

 .controller('Controller1',function($scope,$rootScope,$routeParams){
 $scope.name = 'Controller1';
 $scope.params = $routeParams;
 $scope.formData = {
            checkboxes: {}

                   };
 $scope.demos = [
                 { 'Account':'abc.com',
                   'Custid': 125000,
                    },
                   {'Account':'abc.com',
                   'Custid': 125001, },
                     { 'Account':'abc.com',
                   'Custid': 125002,}
                 ]


         })

I am new to angular js and any help/pointers would be really helpful.




Angularjs - Checkbox - count multiple selected/unselected items

how to count the number of selecte/unselected checkbox items using angularjs?

my html

    <label class="col-xs-5  pull-left" style="font-weight: bold; margin-left: 4px; margin-top: -17px;" >You have choose <font size="3" color="green"></font> Customer(s)</label>

<tr ng-repeat="item in $data " >
             <td width="30" style="text-align: left" header="\'smsChkbx\'">
           <label>
            <input type="checkbox" class="ace" name="someList[]" value="" ng-model="checkboxes.items[item.somename]" />

checkbox function

 $scope.$watch('checkboxes.items', function(values) {
                        if (!$scope.mydata) {
                            return;
                        }
                        var checked = 0,
                            unchecked = 0,
                            total = $scope.mydata.length;
                        angular.forEach($scope.mydata, function(item) {
                            checked += ($scope.checkboxesSms.items[item.somename]) || 0;
                            unchecked += (!$scope.checkboxesSms.items[item.somename]) || 0;
                        });
                        if ((unchecked == 0) || (checked == 0)) {
                            $scope.checkboxes.checked = (checked == total);
                        }

                        **if(checked != 0 && unchecked != 0){
                            $scope.checkedResult++;
                        }**                    
                        $scope.tableParamsSms.reload();                                                
                         console.log($scope.checkedResult);
                        console.log((checked != 0 && unchecked != 0));
                        angular.element(document.getElementById("select_Sms")).prop("indeterminate", (checked != 0 && unchecked != 0));
                    }, true); 

counts properly when i check for first time, the issue is it wlll also count when i uncheck the checked one

also want to count when its checked by multiple check option




Dojo Checkbox Label

Hi i have to create an Checkbox which is set up in JavaScript Code. For that we are using DOJO in our project. This Checkbox should just be visible for one project so i can't insert on html side. To realise the Checkbox wasn't a problem and also the visability. But i can't set a label which should be next to the Checkbox.

HTML Code:

JavaScript Code:

        if (this.createCheckInput)
        {
                this.checkInput = new CheckBox({
                    name: "checkBox",
                    id: "checkId",
                    value: "agreed",
                    innerHTML: "Publish", //Label i wan't to create
                    onChange: lang.hitch(this, function (p)
                    {
                            if (p == true) {

                            this.checkboxChecked = p;
                            }
                    })
                }, this.publishCheckbox);

        }

I Also tried it with another JavaScript Element but there is no DOJO Library I can use i just find the Textarea but the user should not be able to change the text.

JavaScript Code 2:

        //create title for checkbox
        if (this.createInputLabel)
        {
            this.showInputLabel = new Textarea ({
                value : 'Publish after upload'
            },this.publishCheckboxLabel);
        }

Thanks for helping :)




Programming gridview checkboxes to auto check relevant rows

I want to program the checkboxes so that if a row is selected, the program will read the value in the first column of the gridview row and automatically check all rows that also have that value in their first column. I was able to do this using an array to store the value and running through each row, checking if this value was a match. If it matched, the checkbox was checked. This worked but was a very limited solution. When I tried to reverse the action, it simply rechecked that value automatically because that value was still in the array and I did not know how to distinguish between a check or un-check action. It was solely based on a change event.

        int count = 0;
        foreach (GridViewRow gvrow in GridView1.Rows)
        {
            CheckBox chk = (CheckBox)gvrow.FindControl("chkRow");

            if (chk.Checked)
            {
                count++;
            }
        }
        string [] dnum = new string[count];
        int counter = 0;

        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox myCheckBox = row.FindControl("chkRow") as CheckBox;
            if (myCheckBox.Checked)
            {
                if (counter > 0)
                {
                    int number = counter - 1;
                    if (row.Cells[1].Text != dnum[number])
                    {
                        dnum[counter] = row.Cells[1].Text;
                        counter++;
                    }
                }
                else
                {
                    dnum[counter] = row.Cells[1].Text;
                    counter++;
                }
            }
        }
        return dnum;
    }

The array dnum should return the first column values for the checked rows . With this I can run through each row and check if any checkboxes need to be checked.

 foreach (GridViewRow gvrow in GridView1.Rows)
 {
     CheckBox ChkBox = (CheckBox)gvrow.FindControl("chkRow");
     if (ChkBox.Checked == true)
     {
        foreach (string s in first)
        {
           if (gvrow.Cells[1].Text == s)
           {
              ChkBox.Checked = true;
           }
        }
     }

But now I am unable to figure out how to reverse the process, i.e when I uncheck one, all with the same first column value must uncheck, instead it just rechecks because that value is still in the array. I am open to completely different methods.

Many thanks, Nicolas




How to enable/disable a button when Datatables has checkbox selected row

How can I enable/disable my button when there is a selected checkbox row in my datatable?

var pctoreceive = $('#pcToReceive').DataTable({
           'columnDefs': [{
                'targets': 0,
                'searchable': false,
                'orderable': false,
                'className': 'dt-body-center',
                'render': function (data, type, full, meta) {
                    return '<input type="checkbox" name="id[]" value="'
                       + $('<div/>').text(data).html() + '">';
                }
            }],

I've shorten my code. Above shows that I added a new column for checkbox select

enter image description here

Those two button must be disabled when there is no selected row. Otherwise enable

$('#rc-select-all').on('click', function() {
    // Check/uncheck all checkboxes in the table
    var rows = pctoreceive.rows({
        'search': 'applied'
    }).nodes();
    $('input[type="checkbox"]', rows).prop('checked', this.checked);
});

// Handle click on checkbox to set state of "Select all" control
$('#pcToReceive tbody').on('change', 'input[type="checkbox"]', function() {
    // If checkbox is not checked
    if (!this.checked) {
        var el = $('#rc-select-all').get(0);
        // If "Select all" control is checked and has 'indeterminate' property
        if (el && el.checked && ('indeterminate' in el)) {
            // Set visual state of "Select all" control 
            // as 'indeterminate'
            el.indeterminate = true;
        }
    }
});