mardi 31 mai 2016

To insert unchecked value of a check box into database

I need help in inserting the unchecked value of a check box into mysql database using servlet.

Work Flow:

1.From a list of check box values the user checks some of the values and the remaining values are set unchecked

2.After selecting the values the user hits the save button

3.On clicking the save button,the checked values should be stored in one table and the unchecked values should be stored in another table

Issue

I have used the general method to insert the values into database,for me the checked values are getting inserted into one table(pdt_list).In the same way I need to insert the unchecked values into another table say(no_pdt_list). Both the insertion should happen once the save button is clicked.

This is my code

products.jsp

<%@page import="java.util.List"%>
    <%@page import="web.Products"%>
    <%@page import="java.util.ArrayList"%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
     <form method="post" action="Save_Products">   
<b>          
            Brand Name:<font color="green">
            <% String brand_name=(String)session.getAttribute("brand_name");
       out.print(brand_name);%> 
        <c:set var="brand_name" value="brand_name" scope="session"  />
       </font></b>         
            <table>            
                <tr>                
                    <th> Products</th> 
                    <th> Description </th>
                </tr>
                <tr>
               <td> <b><%
      List<Products> pdts = (List<Products>) request.getAttribute("list");
      if(pdts!=null){
        for(Products prod: pdts){
           out.println("<input type=\"checkbox\" name=\"prod\" value=\""  + prod.getProductname() + "\">"  + prod.getProductname()+"<br>");
            } %> </b></td>   

            <td><%for(Products prod: pdts){
            out.println("<input type=\"text\" name=\"desc\" style=\"width:50px; height:22px\"/><br/>"); 
        } 

      }  
            %> </td>  

        </tr>
        <br/>
        <br/>
        <tr><td align="center">  <input type="submit" value="Save" name="save"/> </td></tr> 
            </table>
    </form>
    </body>
    </html>

Servlet code

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;


public class Save_Products extends HttpServlet {
 static final String dbURL = "jdbc:mysql://localhost:3306/pdt";
     static final String dbUser = "root";
     static final String dbPass = "root";
    @Override
     public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         response.setContentType("text/html;charset=UTF-8");    
        PrintWriter out = response.getWriter();
            ResultSet rs=null;
            Connection connection = null;  
            try{
      HttpSession session = request.getSession();
    String brand_name =(String) session.getAttribute("brand_name");
String [] prod_list = request.getParameterValues("prod");
String [] desc_list = request.getParameterValues("desc");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection (dbURL,dbUser,dbPass);

String sql="insert into pdt_list(brand_name,product_name,desc)values(?,?,?)";
PreparedStatement prep = connection.prepareStatement(sql); 
int num_values = Math.min(prod_list.size(), desc_list.size());

int count_updated = 0;
for(int i = 0; i < num_values; i++){
    prep.setString(1, brand_name);
    prep.setString(2, prod_list[i]);
    prep.setString(3,desc_list[i]);
    count_updated += prep.executeUpdate();
}
if(count_updated>0)
{    
   out.print("Products Saved Successfully...");
 RequestDispatcher rd=request.getRequestDispatcher("Save_Success.jsp");    
            rd.forward(request,response);    
}
else{
    RequestDispatcher rd=request.getRequestDispatcher("Save_Failure.jsp");    
            rd.forward(request,response);   
}

prep.close();
       }
     catch(Exception E){
//Any Exceptions will be caught here
System.out.println("The error is"+E.getMessage());

    }  

        finally {
            try {
                connection.close();
            } 
        catch (Exception ex) {
                System.out.println("The error is"+ex.getMessage());
            }
                }

}

}




Alert message when sum of checkboxes is greater than a specific number

I need your help with something I am trying to create.What I want to build is an alert message displaying to user screen when the sum of the values of the checkboxes is greater than a specific number which is stored in the database table.The thing is that I am using php to echo the checkboxes form..

Here is the form:

echo '

     <div>
       <div class="feed-activity-list">
         <div style="border: 0.5px solid green; border-right-style:none;" class="input-group m-b"><span class="input-group-addon"> <input type="checkbox" name="opt" value="'.$points.'"></span>
            <div class="feed-element">
              <a href="profile.html" class="pull-left">
              <img alt="image" class="img-circle" src="'. $row_select4['image_url']. '">
              </a>
            <div class="media-body ">
              <div class="ibox-tools">
                  <span class="label label-primary">ΔΙΑΘΕΣΙΜΟ</span><br><br>
                  <span class="label label-warning-light pull-right"><strong>'  .$row_select4['points'].  '</strong> Πόντοι</span>
              </div>
                  <strong>'  .$row_select4['title'].  ' </strong> '   .$row_select4['description'].  ' <br>
                  <small class="text-muted">Διάρκεια: <strong>'  .$row_select4['start_date'].  ' - '   .$row_select4['end_date'].  ' </strong></small>
              <div class="well">
                                                        '  .$row_select4['description'].  '
           </div>
         </div>
       </div>
     </div>

  </div>'  ;

And the submit button (outside the php script):

<button type="submit" class="btn btn-w-m btn-primary">ΕΞΑΡΓΥΡΩΣΗ</button> 
</form>




Update record if checkbox is checked

I'm trying to check if the checkbox has been selected, and if so to then update all records where a particular column (update_checkbox - a boolean value in my table) is true.

The main aim is so only one record in the column can ever be 'true', and when a new record is created/edited and the checkbox checked then this record will be true and turn the other to false.

Under models/article.rb:

class Article < ActiveRecord::Base
  if :update_checkbox == '1'
    #find records where update_checkbox is true & update to false
    Article.where(:update_checkbox => true).update_all(:update_checkbox => false)
  end
end

I can update my records fine but it's the 'if checkbox is checked' part I'm having trouble with - currently when I create a new record with update_checkbox checked the row with this flag set to true is not being set to false. Any help is appreciated!




passing value of checkbox to jquery function

I have a simple form with several bootstrap toggle checkboxes like so:

<input type="checkbox" value="8" name="fee_hidden8" id="fee_hidden8" class="btoggle" data-toggle="toggle" data-on="<i class='glyphicons glyphicons-eye-close'></i> Hidden" data-off="<i class='glyphicons glyphicons-eye-open'></i> Visible" data-onstyle="danger" data-offstyle="success">
<input type="checkbox" value="9" name="fee_hidden9" id="fee_hidden9" class="btoggle" data-toggle="toggle" data-on="<i class='glyphicons glyphicons-eye-close'></i> Hidden" data-off="<i class='glyphicons glyphicons-eye-open'></i> Visible" data-onstyle="danger" data-offstyle="success">

Where the 'id' of the record to be updated is the 'value' of the checkbox.

I want to pass the "value" of the checkbox to my jquery function -- or -- grab the assigned value that contains the id of the record to update:

  $(function() {

    $('.btoggle').change(function() {
        if($(this).prop('checked'))
        {var st = 'Yes'}
        else
        {var st = 'No'};

        // not sure what to do here
        //var fx = $(this).val();
        var fx = $(this).attr('value');
        alert(fx);

        $.post("tsafunctions.cfc", {
            method: 'visiblehidden',
            fc: fx,
            status: st
            });

    })
  });




How to create a single function that handles checkbox selection?

I'm working on this simple checkbox selection that works just fine when selecting a single row or selecting all the rows. However, I would like to have only one function that handles the checkbox selection. As of right now I have 3 functions called: customer_name_func , customer_lastname_func and customer_email_func. Can someone help me on this please? Here's my code that works just fine:

$(document).ready(function() {

  $("#checkAll").change(function() {
    $("input:checkbox").prop('checked', $(this).prop("checked"));
    $(customer_name_func);
    $(customer_lastname_func);
    $(customer_email_func);
  });

  var customer_name_func = function() {
    if ($("#customer-name-checkbox").is(":checked")) {
      $('#customer-name-inputField').prop('disabled', false);
    } else {
      $('#customer-name-inputField').prop('disabled', 'disabled');
    }
  };
  $(customer_name_func);
  $("#customer-name-checkbox").change(customer_name_func);

  var customer_lastname_func = function() {
    if ($("#customer-lastname-checkbox").is(":checked")) {
      $('#customer-lastname-inputField').prop('disabled', false);
    } else {
      $('#customer-lastname-inputField').prop('disabled', 'disabled');
    }
  };
  $(customer_lastname_func);
  $("#customer-lastname-checkbox").change(customer_lastname_func);

  var customer_email_func = function() {
    if ($("#customer-email-checkbox").is(":checked")) {
      $('#customer-email-inputField').prop('disabled', false);
    } else {
      $('#customer-email-inputField').prop('disabled', 'disabled');
    }
  };
  $(customer_email_func);
  $("#customer-email-checkbox").change(customer_email_func);

});
<script src="http://ift.tt/1qRgvOJ"></script>
<form>
  <input type="checkbox" id="checkAll" />Select All
  <br/>
  <input type="checkbox" id="customer-name-checkbox" name="customer-name-checkbox" value="yes">
  <!---echo php customerName value from WS--->
  <label for="pizza">Name&nbsp;&nbsp; LastName&nbsp;&nbsp; Phone Number</label>
  <input type="email" name="name" id="customer-name-inputField" />
  <br/>
  <br/>

  <input type="checkbox" id="customer-lastname-checkbox" name="customer-lastname-checkbox" value="yes">
  <!---echo php customerLastName value from WS--->
  <label for="pizza">Name&nbsp;&nbsp; LastName&nbsp;&nbsp; Phone Number</label>
  <input type="email" name="email" id="customer-lastname-inputField" />
  <br/>
  <br/>

  <input type="checkbox" id="customer-email-checkbox" name="customer-email-checkbox" value="yes">
  <!---echo php customerPhoneNumber value from WS--->
  <label for="pizza">Name&nbsp;&nbsp; LastName&nbsp;&nbsp; Phone Number</label>
  <input type="email" name="email" id="customer-email-inputField" />
  <br/>
  <br/>

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



If URL contains anchor link check matching checkbox

Is it possible to see if a URL contains a hash anchor link

http://ift.tt/1UfaaFy

Then check the matching checkbox on the page

<input type="checkbox" value="example" id="example">




How to implement the multi-selection with angular either checkboxes / selectbox

Can any one please suggest me the helpful directive to implement the feature with multiselection.

The i/p as array format. eg: [1,2,4,5,6,7,8,9]

I used the below directives, - angular ui.select : When I save it, sends the strings correctly. But When i get this values the select box is select with commas. - checklist-model : Saving properly. Get the value is coming as single string.

eg:

items = [1,2,3,4,5,6,7] Save: [4,6] Get : 4,6 (selected as 3 items)

sorry for incorrect english words.




Dynamic filter table with checkboxes in ng-repeat

I am tying to filter my table by using checkboxes, I succeed doning this with radio buttons with the following code:

<label class="checkbox-inline" >
       <input type="radio" ng-model="term" value="HT1"/> HT1
       <input type="radio" ng-model="term" value="HT2"/> HT2
       <input type="radio" ng-model="term" value="VT1"/> VT1
       <input type="radio" ng-model="term" value="VT2"/> VT2
</label>
<tr ng-repeat="course in vm.courses|filter:term">

I realize that the same no not work when using checkboxes because all checkboxes gets the same ng-model. But how do I do this with checkboxes? I would like to use javascript and not angular if I have to use a script




How to collect all chexbox elements insiide of a div?

I have a big div element and there are multiple div and input (checkbox type) tags inside of it. I want to check that if all checkboxes are checked or no. I try the following JQuery snippet to refer to all checkboxes inside the div:

$('div#mainDiv-checkboxes input[type=checkbox]').each(function(){
        //my logic
    });

but it doesn't get all checkboxes. What is the reliable jquery selector for this kind of situation? there is no order for the position of input elements in my page. I mean there can be everywhere inside of the main div.




If no checkbox is checked, display an error message - Laravel

I tried a couple of things to display an error message. The idea is that the user can add tags to his products. On my main view is a table with all products listed. Every line of the table have his own a checkbox and the user can select any product he want, to add some tags to these products on the next page.

My problem is, I want to display a flash message that tells the user, he haven't checked any checkboxes. Nothing more then that. Currently he gets directed to the next page with no product selected.


My tries

Thats the controller function, the user getting directed to, if he submits the form.

public function edit() {

// some non important controller code 
if(count(Input::get('id')) == 0)
{
    Session::flash('danger', 'Sie haben kein Produkt gewählt!');
    return redirect()->back();
}
else
{
    return view('layout.edit.productedit', [
        'ids' => $data,                  // non important variables
        'products' => $product_name        
    ]);
}

}

and in my view:

@if (Session::has('danger'))
    <div class="alert alert-danger"></div>
@endif

That didn't worked so well. The user gets his error message displayed but if he does everything right, the next page also gets this error message AND the tagging request doesn't work anymore.

So I need another way to check if the user has selected any checkbox and tell him, he need's to select at least a single checkbox to continue adding tags.

Maybe with a Javascript/Jquery solution or another way in laravel.

Thanks for taking your time and I'm sorry for my bad english.




Retain checked status of checkbox and add new values to check box

I have unique query, I want the checkboxes to remain checked after ajax makes the call to DB and gets some extra values. Suppose there are four values checked before ajax call and after ajax call to DB there are 6 values out of which four are same values as checked ones. I need the four of the initial values to be checked and other two new values to be unchecked. Is there any way to do this ?




Automatic selection of checkbox in the custom list view

I am building a Android apps Uninstaller and the list contains list of package names, checkbox to chose which one to uninstall. the problem is that when the list became longer than the phone screen and the scrolling is active; when i select a check box , a second one is automatically selected in the bottom of the list.

the problem is the automatic selection of the second checkbox; please let me know how can i fix it ?? Here the code of main Activity.

public class Mode extends Activity implements android.widget.CompoundButton.OnCheckedChangeListener
{
    PackageManager packageManager;
    ListView apkList;

    List<PackageInfo> packageList1=new ArrayList<PackageInfo>();
    @Override
    public void onCreate(Bundle savedInstanceSpace)
    {
        super.onCreate(savedInstanceSpace);
        setContentView(R.layout.apklist_item1);
        apkList = (ListView) findViewById(R.id.applist);

        packageManager=getPackageManager();
        List<PackageInfo> packageList= packageManager.getInstalledPackages(0);

        for(PackageInfo pi : packageList)
        {
            boolean b = isSystemPackage(pi);
            if(!b)
            {
                packageList1.add(pi);

            }
        }


        Collections.sort(packageList1,  new Comparator<PackageInfo>() {
            @Override
            public int compare(PackageInfo lhs, PackageInfo rhs) {
                return lhs.applicationInfo.loadLabel(getPackageManager()).toString().compareTo(rhs.applicationInfo.loadLabel(getPackageManager()).toString());

            }
        });



        ApkAdapter apkAdapter =new ApkAdapter(this, packageList1, packageManager);
        apkList.setAdapter(apkAdapter);


    }

    private boolean isSystemPackage(PackageInfo pkgInfo) {
        return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
                : false;
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        int pos = apkList.getPositionForView(buttonView);


        if (pos != ListView.INVALID_POSITION) {
            PackageInfo packageInfo = (PackageInfo) apkList.getItemAtPosition(pos);
            AppData appData = (AppData) getApplicationContext();
            appData.setPackageInfo(packageInfo);

        }

Adapter class:

public class ApkAdapter extends  BaseAdapter {


    List<PackageInfo> packageList;
    Activity context;
    PackageManager packageManager;
    boolean itemChecked;
    public ApkAdapter(Activity context, List<PackageInfo> packageList,
                      PackageManager packageManager) {
        super();
        this.context = context;
        this.packageList = packageList;
        this.packageManager = packageManager;
    }

    private class ViewHolder {
        TextView apkName;
        TextView apkInstall;
        CheckBox cb;
    }

    public int getCount() {
        return packageList.size();
    }

    public Object getItem(int position) {
        return packageList.get(position);
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        LayoutInflater inflater = context.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.apklist_item, null);
            holder = new ViewHolder();

            holder.apkName = (TextView) convertView.findViewById(R.id.appname);
            holder.apkInstall=(TextView)convertView.findViewById(R.id.appInstall);
            holder.cb.setChecked(isEnabled(position));

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

PackageInfo         packageInfo = (PackageInfo) getItem(position);
           Drawable appIcon = packageManager
                .getApplicationIcon(packageInfo.applicationInfo);
        String appName = packageManager.getApplicationLabel(
                packageInfo.applicationInfo).toString();
        appIcon.setBounds(0, 0, 50, 50);
        holder.apkName.setCompoundDrawables(appIcon, null, null, null);
        holder.apkName.setCompoundDrawablePadding(15);


        holder.apkName.setText(appName);
       holder.cb.setTag(position);

      File file=new File(packageInfo.applicationInfo.sourceDir);

        long sizeInBytes =  file.length();

        double sizeInMb=sizeInBytes/(1024);

        holder.apkInstall.setText(String.valueOf(sizeInMb)+"KB" );


        return convertView;
    }


}

        }

XML File

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">
    <Button
        android:text="Uninstaller"
        android:onClick="uninstall"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />



    <ListView
        android:id="@+id/applist"
        android:paddingTop="40dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayou





  <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://ift.tt/nIICcg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <TextView
            android:id="@+id/appname"
            android:padding="@dimen/activity_horizontal_margin"
            android:textColor="#006400"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:paddingTop="5dp"
            android:textSize="20sp"
            android:paddingLeft="10dp"
            android:paddingBottom="5dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/appInstall"
            android:layout_marginTop="20dp"
            android:padding="@dimen/activity_horizontal_margin"
            android:textColor="#006400"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:paddingTop="5dp"
            android:textSize="15sp"
            android:paddingLeft="10dp"
            android:paddingBottom="5dp"
            android:textStyle="bold" />
        <CheckBox
            android:id="@+id/cb"
            android:layout_alignParentRight="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RelativeLayout>




Listview ItemChecked how to check

I'm loading some text into my listview lvPersons what I want to do is, if in the column with index 0 have the value 1 the checkbox is checked if its 0 is unchecked and when I click in the checkbox it should check and uncheck but at the same time change to value to 0 or 1 but I can't do this, because when I give a load the it replaces the 1 to 0 and uncheck all the checkboxes my code is the follow:

private void btnLoadList_Click(object sender, EventArgs e)
{            
    //My load funcion is here

    //This code after the load if getting skipped to private void lvPersons_ItemChecked(object sender, ItemCheckedEventArgs e) so this one is not executing after the load of items


    foreach (ListViewItem ActiveItem in lvPersons.Items)
    {
        if (ActiveItem.SubItems[0].Text == "1")
        {
            ActiveItem.Checked = true;
        }
    }
}

#endregion

private void lvPersons_ItemChecked(object sender, ItemCheckedEventArgs e)
{
    foreach (ListViewItem CheckChangeNow in lvPersons.Items)
    {
        //This  code here is the same that is up in the button but with this one here they will appear check but they will not uncheck
        if (CheckChangeNow.SubItems[0].Text == "1")
        {
            CheckChangeNow.Checked = true;
        }
        //End

        //If i remove the one upthere and just leave this one after the load it will replace all the items to 0 and they will appear unchecked
        if (CheckChangeNow.Checked == true)
        {
            CheckChangeNow.SubItems[0].Text = "1";
        }
        else
        {
            CheckChangeNow.SubItems[0].Text = "0";
            CheckChangeNow.Checked = false;
        }
    }
}




using jquery - when a checkbox with class .a is checked, check preceding box with class.b [duplicate]

This question already has an answer here:

When any checkbox with class .child-term is checked, I automatically need to check the preceding checkbox with class .parent-term.

I only want to check the preceding .parent-term class not all the checkboxes that have .parent-class. Same goes for the .child-term class. Any checkbox with .child-term only affects the .parent-term above.

If the .parent-term class was checked from a .sub-term checkbox the .parent-term can remain checked when all the associated .sub-term boxes are unchecked.

I have tried various solutions, but I can't figure it out.

I started a jsfiddle.

<ul class="cpt-terms-checkbox">
    <li class="parent-term church" id="category-church"><input id="church"
    name="church" type="checkbox" value="church">Church</li>

    <li><small>Sub Categories:</small></li>

    <li class="child-term elder" id="category-elder"><input id="elder"
    name="elder" type="checkbox" value="elder">Elder</li>
    <li class="child-term interim-pastor" id="category-interim-pastor">
    <input id="interim-pastor" name="interim-pastor" type="checkbox" value=
    "interim-pastor">Interim Pastor</li>

    <li class="parent-term law-firm" id="category-law-firm"><input id=
    "law-firm" name="law-firm" type="checkbox" value="law-firm">Law
    Firm</li>

    <li><small>Sub Categories:</small></li>

    <li class="child-term attorney" id="category-attorney"><input id=
    "attorney" name="attorney" type="checkbox" value=
    "attorney">Attorney</li>
    <li class="child-term attorney" id="category-attorney"><input id=
    "attorney" name="attorney" type="checkbox" value=
    "attorney">Paralegal</li>
</ul>




lundi 30 mai 2016

How do I properly store multiple checkboxed values using SimpleForm?

Basically I want to create an option in my form that accepts checkboxes (0 to all values accepted).

I love the structure of enums, because I get the performance speed of storing the integer in the DB, but I can reference the symbol in my code. However, I doubt I can use enum when I am storing multiple values like a checkbox.

So the way I imagine it working best is to just store it as a string that is also an array. So something like this:

#  refactor_rule           :string           default([]), is an Array

Then my form looks like this:

<%= f.input :refactor_rule, collection: ["dry", "concise", "performant"], as: :check_boxes, class: "form-control" %>

The issue with this approach is when I store just 1 or 2 of the options (i.e. not all), this is what the attribute looks like:

q.refactor_rule
=> ["", "dry", "concise"]

Which I hate, because of the empty value at [0].

So my questions are as follows:

  1. What's the most performant way to achieve this? Note that the options in my checkbox are static, but the field needs to accept multiple not 1?
  2. How do I only store the values checked and not empty values?
  3. Is there any way to take advantage of Rails built-in enum functionality even though I am storing multiple values?



Checkbox unchecked when scroll in listview android

I using custom listview in my project and I have one problem. I added checkboxs in row inside listview using addview, but checkbox uncheked when scroll in listview. I tried settag/gettag by position but in my case one row has several checkboxs. so how can I solve this problem? please help me..

public View getView(final int position, View convertView, final ViewGroup parent) {

    View itemView;
    final ViewHolder viewHolder;

    if (convertView == null) {
        itemView = layoutInflater.inflate(R.layout.activity_delivering_partner_item, parent, false);

         viewHolder = new ViewHolder();

        final Deliveryltem deliveryltemPosition = epicerieDelivery_delivering_recipient.selectedDeliveryItem.get(position);

        time = (TextView) itemView.findViewById(R.id. delivering_item_time);
        name = (TextView) itemView.findViewById(R.id.delivering_item_name);
        address = (TextView) itemView.findViewById(R.id.delivering_item_address);
        goods = (TextView) itemView.findViewById(R.id.delivering_item_goods);
        partner_linear = (LinearLayout) itemView.findViewById(R.id.delivering_partner_goods_linear);
        LayoutInflater layoutInflater =
                (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        partner_linear.removeAllViews();

        String purchase_name = "";


            purchase_name = deliveringListActivity.purchase_name_arr.get(deliveringListActivity.purchase_num);


        time.setText(deliveryltemPosition.shipping_time);

        address.setText(deliveryltemPosition.recipient_address);


            for(int k = 0; k< deliveringListActivity.partner_goods_arr.size(); k++){

                final View addView = layoutInflater.inflate(R.layout.activity_delivering_partner_item_row, null);

                TextView goods_name = (TextView) addView.findViewById(R.id.partner_goods_name_row);
                TextView goods_ea = (TextView) addView.findViewById(R.id.partner_goods_ea_row);
                viewHolder.checkbox = (CheckBox) addView.findViewById(R.id.partner_goods_chbox);

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

                        viewHolder.checkbox.setId(position);

                    }
                });

                if(deliveryltemPosition.delivery_order_id.equals(deliveringListActivity.partner_goods_arr.get(k).goods_order_id)){


                    if(deliveringListActivity.partner_goods_arr.get(k).detail_purchase.equals(purchase_name)){

                        goods_name.setText(deliveringListActivity.partner_goods_arr.get(k).detail_product_name);
                        goods_ea.setText(deliveringListActivity.partner_goods_arr.get(k).detail_ea);

                        partner_linear.addView(addView);

                    }else{
                    }

                }else{

                }


        }

        return itemView;


    }else{
        itemView = convertView;

       viewHolder = new ViewHolder();

        if(epicerieDelivery_delivering_recipient.selectedDeliveryItem.size() != 0){

            final Deliveryltem deliveryltemPosition = epicerieDelivery_delivering_recipient.selectedDeliveryItem.get(position);

            time = (TextView) itemView.findViewById(R.id. delivering_item_time);
            name = (TextView) itemView.findViewById(R.id.delivering_item_name);
            address = (TextView) itemView.findViewById(R.id.delivering_item_address);
            partner_linear = (LinearLayout) itemView.findViewById(R.id.delivering_partner_goods_linear);
            LayoutInflater layoutInflater =
                    (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            partner_linear.removeAllViews();


            time.setText(deliveryltemPosition.shipping_time);

            address.setText(deliveryltemPosition.recipient_address);

            String purchase_name = "";

               purchase_name = deliveringListActivity.purchase_name_arr.get(deliveringListActivity.purchase_num);




                for(int k = 0; k< deliveringListActivity.partner_goods_arr.size(); k++){


                    final View addView = layoutInflater.inflate(R.layout.activity_delivering_partner_item_row, null);

                    TextView goods_name = (TextView) addView.findViewById(R.id.partner_goods_name_row);
                    TextView goods_ea = (TextView) addView.findViewById(R.id.partner_goods_ea_row);
                    viewHolder.checkbox = (CheckBox) addView.findViewById(R.id.partner_goods_chbox);


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

                           viewHolder.checkbox.setId(position);

                        }
                    });

                    if(deliveryltemPosition.delivery_order_id.equals(deliveringListActivity.partner_goods_arr.get(k).goods_order_id)){


                        if(deliveringListActivity.partner_goods_arr.get(k).detail_purchase.equals(purchase_name)){

                            goods_name.setText(deliveringListActivity.partner_goods_arr.get(k).detail_product_name);
                            goods_ea.setText(deliveringListActivity.partner_goods_arr.get(k).detail_ea);
                            partner_linear.addView(addView);
                        }else{

                        }
                    }else{

                    }
               }
        }
        return convertView;
    }

}




Automatic check box selection in android custom listview

I'm new to android and building a list and the list contain installed app name with a CheckBox to chose which one to uninstall. for example, the problem is that when the list became longer than the phone screen and the scrolling is active; when i select a check box , a second one is automatically selected in the bottom of the list.

The problem is automatic checkbox selection of check boxes, plz help me.




Developing an AngularJS Directive for table's select all or select single

Our team using Angularjs to developing the SPA. There is a table in the page.And the first column, it had Select All, each row had "Select", if we using the normal logic codes for this feature,it is very easy. But the application had a lot of pages with table, so we should copy the codes each time. we want the same behavior as follow that Angular Material has shown. enter image description here

And I had spend some times to write the directive, the code url is : http://ift.tt/1VrxO7a

angular.module('app.directives').directive('checkAllSingle', [function () {
    return {
        restrict: 'A',
        templateUrl: 'components/directives/check/checkbox.html',

        scope: {
            checked: '=?checked',
            allChecked: '=?allChecked',
            checkType: "@",//字符串
            tableDataList: '=tableDataList',
            selectedItems: '=?selectedItems'//选中内容
        },
        link: function (scope, element, attrs, ctrl, rootScope) {

            scope.$checked = scope.checked;

            scope.$allChecked = scope.allChecked;

            scope.$watch('checked', function (newV, oldV) {
                if (newV != oldV) {
                    scope.$checked = scope.checked;
                }
            });

            scope.$watch('allChecked', function (newV, oldV) {
                if (newV != oldV) {
                    scope.$allChecked = scope.allChecked;
                }
            });


            scope.checkFunc = function () {

                if (scope.checkType == 'all') {
                    scope.tableDataList.forEach(function (item) {
                        item.$checked = scope.$allChecked;
                    });
                } else {
                    scope.checked = scope.$checked;

                    setTimeout(function () {
                        var result = scope.tableDataList.every(function (item) {
                            return item.$checked;
                        });
                        scope.$parent.ctrl.$allChecked = result;
                        scope.$apply();
                    }, 0);
                }
                scope.$parent.ctrl.selectedItems = [];
                setTimeout(function () {

                    scope.tableDataList.forEach(function (item) {
                        if (item.$checked) {
                            scope.$parent.ctrl.selectedItems.push(item);
                        }

                    });
                    scope.$apply();
                }, 1);
            };




        }
    };
}]);

I had done it, but I think the codes in checkbox.directive.js is not very good. Because I used the setTimeout function to do something. For updating the parent variable, I using the parent scope-"ctrl", other workmates maybe don't use the controllerAs in the controller file, so there are a lot of issue in codes. Anybody had implemented these features like this.




Rails Form Select, "InvalidForeignKey"

The error:

Rails Error Page. ActiveRecord::InvalidForeignKey in Devise::RegistrationsController#destroy

So, I'm new to ruby and rails, looking for a way to implement a simple form for whether or not a user wants to be anonymous. When changing the value it works the first time, but to choose the other option the second time the above error comes up.

I'm working with Devise and have other user options like age..etc., but here is the code:

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
  <%= devise_error_messages! %>

 ... [OTHER OPTIONS] ... 

     <%= f.select :anonymous, [['Anonymous', true], ['Yourself', false]] %>

I have anonymous permitted:

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:name, :email, :password) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:name, :email, :password, :current_password, [other options], :anonymous) }
  end

The migration:

class AddAnonymousToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :anonymous, :boolean
  end
end

My goal is to be able to call on a user like so; user.anonymous so that I can handle it accordingly. I'm open to other options/insight as well. Not sure what the delete has to do with any of this.




Need to delay the checkbox order

I need to make this checkbox script delay for 1-2 secound before it change the order of the checked items and the way around.

<ul>
<li><label><input type="checkbox" id="one" />One</label></li>
<li><label><input type="checkbox" id="two" />Two</label></li>
<li><label><input type="checkbox" id="three" />Three</label></li>
<li><label><input type="checkbox" id="four" />Four</label></li>
<li><label><input type="checkbox" id="five" />Five</label></li>
</ul>

Script

var list = $("ul"),
    origOrder = list.children();

list.on("click", ":checkbox", function() {
    var i, checked = document.createDocumentFragment(),
        unchecked = document.createDocumentFragment();
    for (i = 0; i < origOrder.length; i++) {
        if (origOrder[i].getElementsByTagName("input")[0].checked) {
            checked.appendChild(origOrder[i]);
        } else {
            unchecked.appendChild(origOrder[i]);
        }
    }
    list.append(checked).append(unchecked);
});

Have tried to put a timer on, but failed...




What is the purpose or intention of the "Live CD/DVD" checkbox in a VirtualBox VM's Machine Settings Storage screen?

Instructions for installing operating systems inside a VirtualBox virtual machine sometimes advise that the user ensures that the "Live CD/DVD" checkbox is checked. Other instructions don't mention this checkbox at all.

What is the purpose of this checkbox? Does its setting have any functional difference in the operation of a VirtualBox VM?

I am able to boot and install live CDs/DVDs regardless of this checkbox's setting, so I'm confused about why it's even there. I could not find a clear reference to this setting in the VirtualBox User Manual either (did I miss it?), leaving me further perplexed.

Here is a screenshot of the specific item I'm referencing:

enter image description here




Change checkbox value with request status AngularJs

I have this situation, in my app (developed with Ionic+AngularJs) there is a checkbox element, when you click on it an HTTP-request is sended and what I want is, depending on the result of that request, change the check status of the checkbox.

Now, what is happening is, whatever it is the request status, the checkbox changes its check status.

my index.html has this

 <ion-side-menu-content>
      <ion-nav-bar class="bar-dark">

        <ion-nav-buttons side="left">
          <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
          </button>
        </ion-nav-buttons>
      </ion-nav-bar>

      <ion-nav-view name="menuContent"></ion-nav-view>
    </ion-side-menu-content> 

    <ion-side-menu side="left">
      <ion-header-bar class="bar-dark menu-bar">
        <h1 class="title"> Categorías </h1>
      </ion-header-bar>
      <ion-content>
        <ul class="list">
          <a href="#/home" class="item" menu-close>Inicio</a>
          <a href="#/planesEstudio" class="item" menu-close>Planes de Estudio</a>
          <a href="#/calendarioAcademico" class="item" menu-close>Calendario académico</a>
          <a href="#/page/Finales" class="item" menu-close>Finales</a>
          <a href="#/news" class="item" menu-close> Noticias </a>
          <a href="" ng-controller="qrController" on-touch="scanBarcode()" class="item" menu-close> Aulas </a>
     <ion-checkbox class="item item-checkbox-right checkbox-circle" ng-model="notificationEnable" ng-checked="notificationEnable" ng-change="pushNotificationChange()">
              Activar notificaciones
          </ion-checkbox>
        </ul>
      </ion-content>
    </ion-side-menu>

  </ion-side-menus>

and my app.js (which manage this):

  $scope.pushNotificationChange = function(){

      if(localStorage.getItem("notificationEnable")=="true"){
        $cordovaToast.show("Desactivando notificaciones...",'short','bottom');
        unregistration();
      }
      else{
        $cordovaToast.show("Activando notificaciones...",'short','bottom');
        intentandoRegistrarse=true;
        $scope.register();
      }
  }
  $scope.register = function () {
      var config = null;
      config = { "senderID": "674717386103" };

      request = $http({         //hacemos este request para testear la conectividad al backend
                method: "GET",
                url: API+"/qrCode/1",
              });
    request.success(function (){$cordovaPush.register(config).then(function (result) {
                                          $scope.registerDisabled=true;
                                          if (intentandoRegistrarse==true){
                                                    $cordovaToast.show("Notificaciones activadas",'long','bottom');
                                                    intentandoRegistrarse=false;
                                            };
                                }, 
                                function (err) {
                                        console.log("Register error " + err);
                                });
    });

    request.error(function(){
                    if (intentandoRegistrarse==true){
                            $cordovaToast.show("No se pudo activar las notificaciones, asegurate de tener internet e intentá de nuevo!",'long','center');
                            intentandoRegistrarse=false;
              $scope.notificationEnable=false;
              localStorage.setItem("notificationEnable",$scope.notificationEnable);
                    }
                });

  }

I guess I have to use $scope.$apply() but how knows.




Jquery code if checkbox is checked, select all other checkboxes - Working with Laravel

I have a little problem and I still couldn't find a solution. It's about a table in my view and every table row have his own checkbox. There is another main checkbox that should check all other checkboxes, if I'm selecting it.

My problem is that it doesn't work like I want it.

View :

// thats the main checkbox, that should select all other checkboxes 

<th><input type="checkbox" class="select-all"/>All</th>
 // and some other non important <th> fields 


 all table rows 

                @foreach($products as $product)
                    <tr>
                        <td>
                            // every line checkbox
                            <input type="checkbox" name="id[]" value="">
                        </td>
                        <td></td>
                        <td></td>
                        <td>
                            @foreach($product->tags as $tag)
                                ,
                            @endforeach
                        </td>
                        <td></td>
                    </tr>
                @endforeach

Jquery

<script type="text/javascript">
    $(document).ready(function() {
        $('.select-all').on('click', function() {
            if(this.checked) {
                $('.select-all').each(function() {
                    this.checked = true;
                });
            }
            else {
                $('.select-all').each(function() {
                    this.checked = false;
                });
            }
        });
    });
</script>

The Jquery script is okay, If I add the "select-all" class to my <input> tag INSIDE of my foreach loop and also at the field outsite of the loop, all checkboxes getting selected. If I remove the class from the field inside of my foreach loop, it doesn't work anymore. My problem now is that I only want to select all boxes with my main checkbox.. currently, it doesn't matter which checkbox I select, every checkbox will be selected. ( so I don't have the option to select a single row or two.

the select-all class is just in my main checkbox input field, not in my input field inside of my foreach loop.

thanks for taking your time and sorry for my bad english




Add Checkboxes To Woocommerce Order Based On Post Name

I am currently working on a site where the user can select a number of checkboxes when on the woo commerce checkout page.

I need these checkout values to be post names from a custom loop so when they select it, the title of the post shows on the order in the dashboard.

So far I have managed to show the posts on the woo commerce page and add the checkboxes but I don't know how to show multiple values on the backend.

Please see code below.

// Add Fields to cart
add_action( 'woocommerce_checkout_after_customer_details', 'my_custom_checkout_field' );

function my_custom_checkout_field( $checkout ) {

global $post;
echo '<div class="row">';
$args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'product_cat' => 'monthly-tie-subscription', 'orderby' => 'rand' );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post(); global $product;

echo '<div class="two">';

woocommerce_show_product_sale_flash( $post, $product );

if (has_post_thumbnail( $loop->post->ID )) 
    echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); 
else echo '<img src="'.woocommerce_placeholder_img_src().'" alt="Placeholder" width="300px" height="300px" />';

woocommerce_form_field( $post->post_name, array (
'type' => 'checkbox',
'value' => $post->post_name
));


echo'<input type="checkbox" value="' . $post->post_name . '" />' . the_title() . '<br />';

echo '<div class="overlay"></div>';

echo '</div>';
endwhile;
    echo '</div>';
}

// Show on backend
add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');

function my_custom_checkout_field_update_order_meta( $order_id ) {
if ($_POST[$post->post_name]) update_post_meta( $order_id, $post->post_name, esc_attr($_POST[$post->post_name]));
}

Any help would be appreciated.

Thanks in advance.




Update query in PDO with checkboxes

I am pretty new to PDO, and i want to know how i can update my (in this case) products from a status to another status. (for example lent-out to available), their are some values wich have a dutch name. (it's for a dutch project) but i don't think that's the problem here. The DB.php is another file, wich works on other update querys (if i need to put it online i will).

 <?php
    session_start();
    require'class/DB.php';
    require 'class/clsDeleteCat.php';
    $db = new clsDB();
    ?>

    <form action="prodList.php" method="post">
        <select name="product">
            <option value="uitgeleend">Uitgeleend</option>
            <option value="beschikbaar">Beschikbaar</option>
        </select>
        <input type="submit" name="submit" value="Filter"/>
    </form>
    <?php
    $selected_val = $_POST['product'];  // Storing Selected Value In Variable
    $result2 = $db->getRow("SELECT * FROM products WHERE productStatus = '".$selected_val."' ");
    echo "<table>";
    echo "<th>Product naam</th><th>Tijd van uitlenen</th><th>Samenvatting product</th> <th>Product category</th><th>Product status</th><th>Selecteer</th>";
    while ($row = $result2->fetch()) {
        unset($prodName, $prodSummary);
        $prodName = $row['productName'];
        $prodLentTime = $row['lentTime'];
        $prodSummary = $row['productSummary'];
        $prodCategory = $row['productCategory'];
        $prodStatus = $row['productStatus'];
        echo "<tr><td  hidden>" . $row['productId'] . "</td>";
        echo "<tr><td>" . $prodName . "</td>";
        echo "<td>" . $prodLentTime . "</td>";
        echo "<td>" . $prodSummary . "</td>";
        echo "<td>" . $prodCategory . "</td>";
        echo "<td>" . $prodStatus . "</td>";
        ?>
        <td><input type="checkbox" name="checkbox[]" value="<?php echo $row['productId'];?>"/></td>
        <?php
    }
    ?>
    </table>
    <form method="post">
        <input type="submit" name="submit1" value="updaten">
    </form>
</div>
</body>
</html>
<?php
if(isset($_POST['submit1']))
{
    ini_set('memory_limit', '64m');
    if (isset($_POST['checkbox']))
    {
        $check = rtrim(implode($_POST['checkbox'], ','));
        // Alle aangevinkte rijen worden verwijderd
        $updateRows = $db->updateRow("UPDATE products SET productStatus = 'available' WHERE productId IN ($check)");


        // If rows get updated refresh the page
        if ($updateRows == TRUE)
        {
            header("Refresh:0");

        } // If something went wrong
        else
        {
           echo "Something failed";
        }
    }
}

?>




Angular js checkbox

I want to print the values of a array based on the checkbox associated with it. Find the code below

Javascript:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName= [{name:"John",selected:"false"},{name:"Anil",selected:"false"},{name:"Kumar",selected:"false"}];
    $scope.lastName= "Doe";
    $scope.name1=[],
    $scope.addname=function(){
    angular.forEach($scope.firstName, function(name,selected){
  if(selected=="true") {
  alert(name);
    $scope.name1.push(name)
  }
});
 }
 });

html:

<div ng-app="myApp" ng-controller="myCtrl">
<table >

<tr ng-repeat="first in firstName">
<td><input type="Checkbox" ng-model="first.selected"></td>

</tr>
<tr><td><input type="Button" ng-click="addname()" value="Submit" ng-model="lastName"></td></tr>

<tr ng-repeat="nam in name1"></tr>
</table>
</div>




How to save checkbox state in listview using sharedpreference

I have checkboxes in listview, i want checkbox states to be saved when i click on it,now when i resume my app ,all the checkboxes will be unchecked.I am trying to develop TODO List app where list row textview will be striken and checkbox will be checked, how can i save checkbox state and striken textview into sharedpreference and load.

 protected void onCreate(Bundle saved) {
        super.onCreate(saved);
        setContentView(R.layout.cbox_list);
        Listvw = (ListView) findViewById(R.id.clistvw);
        Listvw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                cText = (TextView) view.findViewById(R.id.ctext);
                cBox = (CheckBox) view.findViewById(R.id.cbox);
                cBox.setChecked(true);
                //Toast.makeText(getActivity(),"Clicked",Toast.LENGTH_LONG).show();
                cText.setPaintFlags(cText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                //boolean value=cBox.isChecked();
                int b = Listvw.getAdapter().getCount();
                for (int i1 = 0; i1 < b; i1++) {
                    if (cBox.isChecked()) {
                        SharedPreferences spf = PreferenceManager.getDefaultSharedPreferences(CBox_InListView.this);
                        SharedPreferences.Editor edit = spf.edit();
                        edit.putBoolean("name"+i1, cBox.isChecked());
                        edit.commit();
                    }
                }
            }
        });

        model = new CheckModel[12];
        model[0] = new CheckModel("Item1", 0);
        model[1] = new CheckModel("Item", 0);
        model[2] = new CheckModel("Item", 0);
        model[3] = new CheckModel("Item", 0);
        model[4] = new CheckModel("Item", 0);
        model[5] = new CheckModel("Item", 0);
        model[6] = new CheckModel("Item", 0);
        model[7] = new CheckModel("Home Head", 0);
        model[8] = new CheckModel("Item", 0);
        model[9] = new CheckModel("Item", 0);
        model[10] = new CheckModel("Item", 0);
        model[11] = new CheckModel("Item", 0);
        CustomAdapter adpter = new CustomAdapter(this, model);
       int c=Listvw.getAdapter().getCount();
        for(int i=0;i<c;i++)
        {
            SharedPreferences pf=PreferenceManager.getDefaultSharedPreferences(CBox_InListView.this);
            boolean chkbx=pf.getBoolean("name"+i,false);
            if(chkbx){
                cBox.setChecked(true);
            }else{
                cBox.setChecked(false);
            }
        }
        Listvw.setAdapter(adpter);




dimanche 29 mai 2016

how to call CheckBox CheckedChanged Event from javascript

i want to call CheckBox_CheckedChanged Event from javascript code .

my code is:

<script>
    $('#CheckBox').prop('checked', true);

    $("#CheckBox").change(function () {

            <% CheckBox_CheckedChanged(null, null); %>

    });

</script>




select checkbox on row click in ui-grid using angularjs

I am new to angular js. and i want to select the check box when i click on the row to edit that particular cell.I have taken celltemplate to show the checkbox in the ui-grid.but now when i click on the row the row gets selected but the checkbox in that row is not getting selected.

This is my grid-

 $scope.myDataSocailMediaMarketing =[];
                                     $scope.gridOptionsSocialMediaMarketing = { 
                                                appScopeProvider: $scope,
                                                data : 'myDataSocailMediaMarketing' ,
//                                              enableCellSelection: true,
//                                              enableRowSelection: false,
                                                enableRowHeaderSelection :false,
                                                enableRowSelection: true,
                                                enableCellEdit: true,
                                                enableHorizontalScrollbar: 0,
                                                enableRowSelection: true,
                                                enableSelectAll: true,
                                                enableFullRowSelection : true,
                                                  rowEditWaitInterval: -1,
                                                columnDefs: [
                                                             {
                                                                 cellClass : 'grid-align',
                                                                 width : '10%',
                                                                 minWidth : '10%',
                                                                 enableCellEdit: false,
                                                                 field: 'select',
                                                                 displayName: me.labelText.ADD_STORY_TABLE_SELECT,
                                                                 cellTemplate: '<div class="ngCellText text-center"><input type="checkbox" ng-model="row.entity.select" ng-click="grid.appScope.checkboxRowClick(row.entity)""/></div>'

                                                             }, 
                                                             {
                                                                 cellClass : 'grid-align',
                                                                 width : '30%',
                                                                 minWidth : '30%',
                                                                 enableCellEdit: false,
                                                                 field: 'category',
                                                                 displayName: me.labelText.ADD_STORY_TABLE_CATEGORY

                                                             },
                                                             {
                                                                 cellClass : 'grid-align',
                                                                 width : '60%',
                                                                 minWidth : '60%',
                                                                 enableCellEdit: true,
                                                                 field: 'descriptionOrExample',
                                                                 displayName: me.labelText.ADD_STORY_TABLE_DESCRIPTION

                                                             }

                                                             ],


                                        };  

in html i have declared it as-

 <div>
 <div class="gridHeightSocialMarketing socialMediaMarketing table" ui-grid-edit ui-grid-row-edit ui-grid-selection ui-grid="gridOptionsSocialMediaMarketing" style="height:242px;">
</div>
</div>  




For loop in php and oracle

I have created a checkbox form with attribute medicine name, stock quantity and quantity. User can tick on any medicine name and for quantity user need to fill by themselves. When i tick and insert quantity for the first two row, my data successfully saved into my database. Below is the image for my checkbox form.

My checkbox form

But when i tick on the second and the third row,the medicine name successfully insert into database, but the quantity insert into my database is 'null'.

My checkbox form

checkbox.php

     <input type="checkbox" name="MEDICINE_ID[]" value="<?php echo $row['MEDICINE_ID'] ?>" id="check_item" align="middle" />
     </div></td>      
     <td align="center">
       <?php
          echo $row ["MEDICINE_NAME"];
       ?>      
     </td>

     <td align="center">
      <?php
         echo $row ["STOCK_QUANTITY"] ," ", $row ["MED_FORM"];
      ?>      
     </td>

    <td><label>
    <input name="quantity[]" type="number" max="<?php echo $row['STOCK_QUANTITY'] ?>" min='1' id="quantity" value="" size="1000" />
    </label></td>

   <?php
      $i++;
   ?>

checkboxprocess.php

  <?php
     $conn = oci_connect("username", "pass", "orcl");

     $matric_No = $_POST['matric_No'];
     $medicine_ID = $_POST['MEDICINE_ID'];
     $quantity = $_POST['quantity'];
     $dates =  $_POST['dates'];

     $size_medicine=sizeOf($medicine_ID);

        for($i=0;$i<$size_medicine;$i++){       
             $statement="insert into stud_med(quantity,matric_No,medicine_ID,dates) 
             VALUES('$quantity[$i]','$matric_No','$medicine_ID[$i]',to_date('$dates','yyyy-mm-dd'))";
             $state = oci_parse($conn,$statement ); 
             oci_execute($state);   
}
   ?>




conditionally hiding & unhiding image folders in android

The following is my requirement: I have a checkbox in my activity. If the checkbox is checked, I will add a '.nomedia' file to hide all the photos in my folder. If the checkbox is unchecked, I will delete the '.nomedia' file, to display all the photos in the folder. My problem is, though the creation/deletion of '.nomedia' file is successful, the hiding/unhiding of the images are not happening in the android gallery app. How can I force the gallery app to show/hide the folder contents according to my checkbox state?

The following is my code:

CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
 if (checkBox.isChecked()) {
                                hideFolder();                                    
                            } else {
                                unHideFolder();                                    
                            }

    private void hideFolder() {
        File targetDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + CONSTANTS.MYFOLDERPATH);
        File noMediaFile = new File(targetDir, ".nomedia");
        try {
            if (!noMediaFile.exists()) {
                noMediaFile.createNewFile();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void unHideFolder() {
        File targetDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + CONSTANTS.MYFOLDERPATH);
        File noMediaFile = new File(targetDir, ".nomedia");
        if (noMediaFile.exists()) {
            noMediaFile.delete();
        }
    }




Enable checkboxes with jqery

i need your help for a simple jQuery script. I have some images with a surrounding a-tag. Next to the images, there are some checkboxes. My goal is, to enable and disable special checkboxes with a click on an image.

thanks!




jQuery .prop not updating checkbox

Been asked before but no solutions found.

Checkboxes on a CF form. The pertinent line of code is

else { 
  $('#SWSC_CC').prop('checked', true);
  $('#SWSC_CC2').val(1); 
  alert('here');
}

SWSC_CC2 is a textbox added for testing.

I hit this line. SWSC_CC2 updates to 1 (it has no value binding) and the alert pops. Checkbox never changes. I'm seeing this in a number of checkboxes in this application. DOM issues? I can think of workarounds but that's messy. No Firebug errors.




From Select option to multiple checkbox

So i have this code where you can choose a specific Sub-genre of music. Right now you can only choose a single sub genre, but how can i code it so you can choose multiple sub-genres (maybe via checkbox) that can be inserted into a database?

    $day = $_POST["day"];
    $month = $_POST["month"];       
    $year = $_POST["year"];     
    $main = $_POST["main"];     

            $ne = "SELECT * FROM genre WHERE genre='0' AND main='$main'";
            $ne_query_run = mysql_query($ne);
    ?>
    <?php
            echo '<form action="site.php?koncert&fire" method="POST">';
            echo '<input type="text" name="day" class="hide" value="'.$day.'"/>';
            echo '<input type="text" name="month" class="hide" value="'.$month.'"/>';
            echo '<input type="text" name="year" class="hide" value="'.$year.'"/>';                                     echo '<input type="text" name="main" class="hide" value="'.$main.'"/>';
            echo '<select name="sub">';
            while($neo = mysql_fetch_assoc($ne_query_run)){

            $sub = $neo['sub'];

            echo '<option value="'.$sub.'">'.$sub.'</option';

            echo'</select><br /><br />';
            }
            echo '<input type="submit" name="submit"/>';
            echo '</form>';     




samedi 28 mai 2016

Android Check box in Simple Adapter with ArrayList

I have a custom adapter Simple which the xml contains a CheckBox , corresponding to the id select ( R.id.selecionar ) .

However in another Activity where I create an ArrayList < HashMap > () called mcommentList (receiving various data from the database via Jason , however works perfectly )

After I click on a button that has onclick argument irpedidos . Clicking this button want to sweep all my arrayList looking for all the elements that are selected ( Checked box true ) and then put on a String all products who are selected .

However the idea that I have to do is wrong, to access the value of the CheckBox

what would be the solution to do what I want ? ERROR LINE: final CheckBox selec = mCommentList.get(i).get(R.id.selecionar);

package melo.gustavo.Deliveryapp;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class VisualizarCardapio extends ListActivity {

    private ProgressDialog pDialog;


    private static final String READ_COMMENTS_URL =
            "http://-------------------/webserviceDelivery/cardapio.php";

    private static final String TAG_NOMEPRODUTO = "title";
    private static final String TAG_POSTS = "posts";
    private static final String TAG_PRECO = "username";
    private static final String TAG_DESCRICAO= "message";

    private JSONArray mComments = null;
    private ArrayList<HashMap<String, String>> mCommentList;

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

    @Override
    protected void onResume() {
        super.onResume();
        new LoadComments().execute();
    }

    public void irpedidos (View v) {

        String texto = "";
        double totalpedido = 0.0;

        for (int i = 0; i < mCommentList.size(); i++) {
          final String nometeste = mCommentList.get(i).get(TAG_NOMEPRODUTO);
          final String preco = mCommentList.get(i).get(TAG_PRECO);

            final CheckBox selec = mCommentList.get(i).get(R.id.selecionar);

                    if (selec.isChecked()) {
                        texto+= nometeste+" :"+preco+"\n";
                    }

                }

   Toast.makeText(VisualizarCardapio.this,texto , Toast.LENGTH_LONG).show();
    }

    public void updateJSONdata() {

        mCommentList = new ArrayList<HashMap<String, String>>();

        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);


        try {

            mComments = json.getJSONArray(TAG_POSTS);

    // looping through all posts according to the json object returned
            for (int i = 0; i < mComments.length(); i++) {
                JSONObject c = mComments.getJSONObject(i);

                String nomep = c.getString(TAG_NOMEPRODUTO);
                String descp = c.getString(TAG_DESCRICAO);
                String precop = c.getString(TAG_PRECO);

                HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_NOMEPRODUTO, nomep);
                map.put(TAG_DESCRICAO, descp);
                map.put(TAG_PRECO, precop);

                // adding HashList to ArrayList
                mCommentList.add(map);

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void updateList() {
    ListAdapter adapter = new MySimpleAdapterCardapio(this, mCommentList,
        R.layout.single_post_cardapio, new String[] {  TAG_NOMEPRODUTO, 
        TAG_DESCRICAO,TAG_PRECO }, new int[] { R.id.title, R.id.message,
                        R.id.username});

        // I shouldn't have to comment on this one:
        setListAdapter(adapter);


        ListView listView = getListView();
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
    public void onItemClick(AdapterView<?> adapter, View arg1, int posicao,
                                    long arg3) {

                //implementar detalhes (adicional, sem salada)

            }
        });
    }

    public class LoadComments extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(VisualizarCardapio.this);
            pDialog.setMessage("Loading Comments...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... arg0) {
            updateJSONdata();
            return null;

        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            pDialog.dismiss();
            updateList();
        }
    }
}

Follow the codes of activitys and xml the same

MySimpleAdapterCardapio .java
    package melo.gustavo.Deliveryapp;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.ImageView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;


    public class MySimpleAdapterCardapio extends SimpleAdapter {


        private static final String TAG_NOMEPRODUTO = "title";
        private static final String TAG_POSTS = "posts";
        private static final String TAG_PRECO = "username";
        private static final String TAG_DESCRICAO= "message";

        private ArrayList<HashMap<String, Object>> results;
        private Context mContext;
        public LayoutInflater inflater = null;

        public MySimpleAdapterCardapio(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
            mContext = context;
            results = (ArrayList<HashMap<String, Object>>) data;
            inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View vi = convertView;
            if (convertView == null)
                vi = inflater.inflate(R.layout.single_post_cardapio, null);

            final HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);

            final TextView tt = (TextView) vi.findViewById(R.id.title);
            tt.setText((CharSequence) data.get(TAG_NOMEPRODUTO));

            TextView tt2 = (TextView) vi.findViewById(R.id.username);
            tt2.setText((CharSequence) data.get(TAG_PRECO));

            TextView tt3 = (TextView) vi.findViewById(R.id.message);
            tt3.setText((CharSequence) data.get(TAG_DESCRICAO));

            final CheckBox selec = (CheckBox) vi.findViewById(R.id.selecionar);

            selec.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    selec.setChecked(isChecked);
                    if (selec.isChecked()) {
                        selec.setText("Selecionado");
                        Toast.makeText(mContext, tt.getText() + " " + isChecked, Toast.LENGTH_LONG).show();
                    }

                    else {
                        selec.setText("Selecionar");
                    }

                }
            });

            //new DownloadTask((ImageView) vi.findViewById(R.id.fotolanchonete)).execute((String) data.get(TAG_FOTOLANC));

            return vi;
        }
    }

single_post_cardapio.xml

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://ift.tt/nIICcg"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#f0f0f0"
        android:orientation="vertical"
        android:weightSum="1">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="@drawable/post_border_style"
            android:orientation="vertical"
            android:layout_weight="6">

            <LinearLayout
                android:id="@+id/box"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="2dp"
                android:background="@drawable/post_background_style"
                android:orientation="horizontal" >

                <CheckBox
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:id="@+id/selecionar"
                    android:layout_weight="3.08"
                    android:text="Selecionar"
                    />

                <LinearLayout
                    android:id="@+id/box2"
                    android:layout_width="206dp"
                    android:layout_height="wrap_content"
                    android:layout_margin="2dp"
                    android:orientation="vertical"
                    android:padding="5dp"
                    android:weightSum="1"
                    android:layout_weight="3.08">

                    <TextView
                        android:id="@+id/title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="bottom"
                        android:paddingBottom="2dip"
                        android:paddingLeft="5dp"
                        android:paddingTop="6dip"
                        android:textColor="#333"
                        android:textSize="16sp"
                        android:textStyle="bold"

                        android:text="Produto: "/>

                    <TextView
                        android:id="@+id/message"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingBottom="2dip"
                        android:paddingLeft="8dp"
                        android:textColor="#888"
                        android:text="Descrição "
                        >
                    </TextView>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal"
                        android:paddingBottom="5dp" >

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="left"
                            android:paddingLeft="5dp"
                            android:text="Preço: ">
                        </TextView>

                        <TextView
                            android:id="@+id/username"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="left"
                            android:textColor="#acacac"
                            android:textStyle="bold" >
                        </TextView>
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

visualizar_cardapio . xml

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://ift.tt/nIICcg"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#fff" >

        <LinearLayout
            android:id="@+id/top_layover"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:background="@drawable/blue_gradient"
            android:orientation="horizontal" >

            <TextView
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:gravity="center"
                android:text="Cardápio"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:layout_width="wrap_content" />
        </LinearLayout>

        <ListView android:id="@android:id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/bottom_layover"
            android:layout_below="@+id/top_layover"
            android:background="#fff"
            android:divider="@android:color/transparent"
            android:scrollbars="none" />

        <LinearLayout
            android:id="@+id/bottom_layover"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:background="@drawable/blue_gradient"
            android:orientation="horizontal"
            android:weightSum="2" >

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical" >
            </LinearLayout>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical" >

                <Button
                    android:id="@+id/btnValorLista"
                    android:onClick="irpedidos"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right"
                    android:background="@drawable/black_button"
                    android:text="Selecionar Produtos" />
            </LinearLayout>
        </LinearLayout>

    </RelativeLayout>




toggle the value of checkboxpreference in Android

I have a checkboxpreference which performs a tasks once it is clicked on. By default, the checkbox is not checked. After successful completion of the task, it is checked.

content of settings.xml:

<CheckBoxPreference
    android:key="@string/premium_support"
    android:title="Premium Support"
    android:summary="Purchase premium support"
    android:defaultValue="false" />

and my implementation so far:

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

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.settings);

    final CheckBoxPreference checkboxPref = (CheckBoxPreference)
    getPreferenceManager().findPreference("premium_support");
    boolean result; // boolean value to store final result

    // set up a listener for checkbox
    checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

            boolean toggle = false;
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                // just for testing to show value of checkbox
                Toast.makeText(getActivity(), "Pref changed to " + newValue.toString(), Toast.LENGTH_LONG).show();

                // if the checkbox is marked
                if (newValue.toString()== "true"){
                    // purchase the product
                    bp.purchase(getActivity(),PRODUCT_ID);
                }
                // if purchase was successful 
                if (bp.isPurchased(PRODUCT_ID)){
                    // display item purchased for testing
                    showToast("Item purchased");

                    // set the checkbox as checked
                    checkboxPref.setChecked(true);

                    // also make purchased boolean to true
                    result = true;
                    showToast("value of purchased is: " + result);

                }else{
                    // otherwise the item was not purchased
                    showToast("Item was not purchased");

                    // uncheck the checkbox 
                    checkboxPref.setChecked(false);

                    // set the result to false
                    result  = false;
                    showToast("value of purchased is: " + result);
                    //toggle = false;
                }
                // also check if it was purchased before
                if (result != true){
                    showToast("Item was not previously purchased");
                    checkboxPref.setChecked(false);
                }
                return toggle;
            }
        });

Everything works as expected. But if the purchase is successful, the checkboxpreference does not change unless clicked on it again.

So the user clicks on the checkbox, it brings the billing box (billing uses Android In-App Billing Library), the user purchase and closes but the checkbox is not marked. The user must click on the checkbox again.

Any idea why this is occurring?




How to check all check boxes in Telerik Kendo Grid

I have a Kendo Grid with check box column. I want to check all check boxes in the grid and keep it across the pages. I have a method CheckAll(), but it checks only the first page of Kendo Grid. How to check all check boxes by one click on the link or button? My code is here:

<div style="text-align:right; font-size: 0.9em;height:28px;position: relative;">

        <span style="float:left;text-align:left;">
            <a href="#" onclick="checkAll();">Check All</a>&nbsp;
            <a href="#" onclick="uncheckAll();">Uncheck All</a>&nbsp;
            <a class="k-button k-button-icontext k-grid-Patient" id="hrefCheckedPatients" href="#" onclick="getChecked();">Export to PDF</a>&nbsp;
            <a href="#" id="lnkPdfDownload" style="display:none;" onclick="$(this).hide();">Download Generated PDF</a>
            <label id="checkedMsg" style="color:red;display:none;"></label>
        </span>

    </div>
 @(Html.Kendo().Grid<RunSummary>()
          .Name("CheckedPatients")          
          .DataSource(datasource => datasource
                .Ajax().PageSize(25)        
                .Sort(sort => sort.Add("UniqueId").Ascending())                        
                .Read(read => read.Action("GetRunSummaries", "PatientReport")))
          .Columns(columns =>
              {

                  columns.Bound(c => c.UniqueId).Title(ELSORegistry.Resources.Views.Home.HomeStrings.UniqueId)
                        .ClientTemplate("<input type='checkbox'  class='primaryBox' id='#= UniqueId #'>#= UniqueId #</input>");
                  columns.Bound(c => c.RunNo).Title(SharedStrings.Run);
                  columns.Bound(c => c.Birthdate).Title(SharedStrings.Birthdate).Format("{0:g}").Filterable(true);

                  columns.Bound(c => c.customAge).Title(SharedStrings.Age)
                         .Filterable(
                             filterable => filterable
                                 .UI("AgeFilter")
                                 .Extra(false)
                                 .Operators(operators => operators
                                     .ForString(str => str.Clear().IsEqualTo("Is equal to"))
                                     )

                       );

                  columns.Bound(c => c.TimeOn).Title(PatientStrings.DateOn)
                      .Format("{0:g}")
                      .Filterable(true);
                  columns.Bound(c => c.TimeOff).Title(PatientStrings.DateOff)
                      .Format("{0:g}")
                      .Filterable(true);
                  columns.Bound(c => c.DischargedAlive).Title(PatientStrings.DischargedAlive).Filterable(true).ClientTemplate("#= DischargedAlive ? 'Yes' : 'No' #");
                  columns.Bound(c => c.ShowSubmitted).Title(PatientStrings.Submitted).Filterable(true).ClientTemplate("#= ShowSubmitted ? 'Yes' : 'No' #");
                  columns.Bound(c => c.SupportTypeEnum).Title(PatientStrings.SupportType).Filterable(true);//.ClientTemplate("#= SupportType ? 'Yes' : 'No' #");
              }
          )
          .Pageable(p => p.PageSizes(new[] {10, 25, 50, 100}))
          .Sortable()
          .Filterable( )
          .Events( e => e.FilterMenuInit("FilterMenuFuncWithAge") ) // apply x [closing box] on pop up filter box
          )
<script type="text/javascript"> 


    function checkAll() {
        $('input').prop('checked', 'checked');
    }

    function uncheckAll() {
        $('input').removeAttr('checked');
    }
</script>




prestashop checkbox does not save values

I'm can't figure out why the checkbox values not save in the database using helpers and Configuration class.

Trying to save some customers ids from my module's setting :

The array :

$custs = Customer::getCustomers();
foreach ($custs as $key => $value) {
  $options[] = array(
        'id_customer' => (int)$value['id_customer'],
        'infos' => $value['firstname'].' '.$value['lastname'].' | '.$value['email']
    );
}

The checkboxes :

'input' => array(
        array(
            'type' => 'checkbox',
            'label' => $this->l('Customers'),
            'desc' => $this->l('Select the Customers.'),
            'name' => 'MY_MODULE_CUSTOMERS',
            'values' => array(
                'query' => $options,
                'id' => 'id_customer',
                'name' => 'infos',
            ),
        ),
)

Thank you.




ng-true-value='0' picking up wrong values

For demo see jsfiddle here and click on the Out of Stock checkbox.

It should only show stock with quantity of 0, but it is also picking up quantity of 30. I think this is becasue it is matching against string values.

I assume issue is with:

ng-true-value='0'

What is best way to fix this? Please can you provide code example?




Checkbox filtering using Jquery

I'm using this code: http://ift.tt/25suGhB to filter categories, however I need the functionality to be slightly different. If more than one filter is checked the item most contain both to be display.

Example:

Checking Category A and B would only display 'AB' not all instances of 'A' and 'B'

HTML:

<ul id="filters">
<li>
    <input type="checkbox" value="categorya" id="filter-categorya" />
    <label for="filter-categorya">Category A</label>
</li>
<li>
    <input type="checkbox" value="categoryb" id="filter-categoryb" />
    <label for="filter-categoryb">Category B</label>
</li>

<div class="item categorya categoryb">A, B</div>
<div class="item categorya">A</div>
<div class="item categorya">A</div>
<div class="item categorya">A</div>
<div class="item categoryb">B</div>
<div class="item categoryb">B</div>
<div class="item categoryb">B</div>

JS:

    $("#filters :checkbox").click(function() {

   var re = new RegExp($("#filters :checkbox:checked").map(function() {
                          return this.value;
                       }).get().join("|") );
   $(".item").each(function() {
      var $this = $(this);
      $this[re.source!="" && re.test($this.attr("class")) ? "show" : "hide"]();
   });
});




Why isn't my javascript/jquery code working as expected for checkboxes

I have a code where I expect my checkboxes to be selected and disabled. When I click Zero, all checkboxes should be highlighted, all checkboxes except zeroth checkbox should be disabled. Similarly for one, two and three radio buttons. This does not seem to happen consistently. I am trying it on chrome browser version 48.0.2564.116. Also, the behavior is horrible on Firefox. Can someone please let me know what I am doing wrong?

<html>
  <head>
    <script src="http://ift.tt/1pD5F0p"></script>
    <script>
      $(document).ready(function(){
        $("input[name=radio_group]").prop("checked", false);
        $("input[type=radio]").click( function( e ){
           var whats_selected = $("input[name=radio_group]:checked").val()
           $("input[type=checkbox]").attr('checked',false );

         //disable all other checkboxes
         for(i=0; i < 4; i++ ){
           var elem = $("input[type=checkbox][name*=checkbox"+i+"]");
           elem.click();
           if( i != whats_selected ){
             elem.prop("disabled", true);
           }else{
             elem.removeAttr("disabled");
           }
         }
        });
      });
    </script>
  </head>
  <body>
    <h1>Checkbox play</h1>
    <h3>My 4 Radio Buttons</h3>

    <input type="radio" name='radio_group' value=0>Zero<br>
    <input type="radio" name='radio_group' value=1>One<br>
    <input type="radio" name='radio_group' value=2>Two<br>
    <input type="radio" name='radio_group' value=3>Three<br>

    <p>And here are my checkboxes</p>    
    <input type='checkbox' id="chkbox0" name="checkbox0" value="checkbox0">Checkbox Zero<br>
    <input type='checkbox' id="chkbox1" name="checkbox1" value="checkbox1">Checkbox One<br>
    <input type='checkbox' id="chkbox2" name="checkbox2" value="checkbox2">Checkbox Two<br>
    <input type='checkbox' id="chkbox3" name="checkbox3" value="checkbox3">Checkbox Three<br>
  </body>
</html>




ArrayAdapter is changing the value of the CheckBox

I don't know what's happening, I've a list of objects and depending of its state it's checked or not (CheckBox). I've tried too many ways, because first of all I wanted to return an ArrayList<myObject> with the state updated, but I don't know why the objects were duplicating... and I ended up creating a TreeSet (don't know if it's the better way but at least the objects now doesn't repeat)... well the thing is that on my Adapter I have this :

final Sessio sessio = getItem(position);
    ALAdapter.add(sessio);
    vh.tvSessioName.setText(sessio.getName());
    vh.cbAssist.setChecked(sessio.isState());
    vh.cbAssist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Toast.makeText(mContext, "chaning", Toast.LENGTH_SHORT).show();
            sessio.setState(isChecked);
        }
    });

AlAdapter is private TreeSet<Sessio> ALAdapter;

this is working fine, the problem is at the time I re-open the dialog because I save the TreeSet on a json with Gson as follows :

Gson gson = new Gson();
String json = mPrefs.getString("ArrayListSesio", "");
Type type = new TypeToken <TreeSet<Sessio>> () {}.getType();
ArrayList<Sessio> obj = gson.fromJson(json,type);
return obj == null ? AlSessio : obj;

This is also working fine... I think the problem is on the Adapter because if I uncked some of the CheckBox and I change the state of the Sessio when I re-open the Dialog it shows the Toast like 15 times... and everytime I scroll up/down the state of the CheckBox changes....

What I'm doing wrong? Is there any other way to instead of save it to a TreeSet save it to an ArrayList?




Issue toggling caps lock with check box in vb .net

I've developed an application (with vb .net) that can toggle caps lock state by clicking on a check box. I've coded the program in such a way that when I click on the checkbox, if it gets checked the caps lock must be turned on and when unchecked it must turn off. Below are the codes.

Public Class Form1

Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)

Private Const VK_CAPITAL As Integer = &H14
Private Const VK_SCROLL As Integer = &H91
Private Const VK_NUMLOCK As Integer = &H90

Private Const KEYEVENTF_EXTENDEDKEY As Integer = &H1
Private Const KEYEVENTF_KEYUP As Integer = &H2

Private Sub checkbutton_caps_CheckedChanged(sender As Object, e As EventArgs) Handles checkbutton_caps.CheckStateChanged

    If checkbutton_caps.Checked = True Then
        Call keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0)
        checkbutton_caps.Image = Image.FromFile("resources\btn_ico_caps_on.png")

    ElseIf checkbutton_caps.Checked = False Then
        Call keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)
        checkbutton_caps.Image = Image.FromFile("resources\btn_ico_caps_off.png")

    End If
End Sub
End Class

Now the problem is it's not working as expected. If I check the checkbox, only the image of the checkbox changes but not the caps lock status. The caps lock status changes only when I click on the check box twice. So I need to click on the check box twice to toggle the caps lock. I suspect there's a problem in the way I've used the conditional statements.




angular price range filter not working

I have made a price range filter, and when the checkboxes are clicked, I want to show only those items that have the price falling in the price range specified by the checkbox

HTML

<div class="checkbox">
    <input type="checkbox" ng-click="includePrice('0,700')" ng-checked=""/> Rs 700 and Below <br/>
    <input type="checkbox" ng-click="includePrice('701,1500')" ng-checked=""/> Rs 701 - 1500 <br/>
    <input type="checkbox" ng-click="includePrice('1501,3000')" ng-checked=""/> Rs 1501 - 3000 <br/>
     <input type="checkbox" ng-click="includePrice('3001,5000')" ng-checked=""/> Rs 3000 - 5000 <br/>
     <input type="checkbox" ng-click="includePrice('5001,100000000')" ng-checked=""/> Rs 5001 and Above
</div>

In the controller, I get the min and maximum of each checkbox into an array and again min and max of that array as the lower and upper limit

Controller

$scope.priceIncludes = [];
$scope.ranges = [];

$scope.includePrice = function(pricerange) {
    var i = $.inArray(pricerange, $scope.priceIncludes);
    if (i > -1) {
        $scope.priceIncludes.splice(i, 1);
        ranges = pricerange.split(',').splice(i, 1);
    } else {
        $scope.priceIncludes.push(pricerange);
    }
    var arrayString = $scope.priceIncludes.join();
    var rangeArray = arrayString.split(',')
    $scope.maxRange = function( rangeArray ){
        return Math.max.apply( Math, rangeArray );
    };
    $scope.minRange = function( rangeArray ){
        return Math.min.apply( Math, rangeArray );
    };
    $scope.ranges[1] = $scope.maxRange(rangeArray);
    $scope.ranges[0] = $scope.minRange(rangeArray);
}

$scope.priceFilter = function(searchResult) {
    if ($scope.priceIncludes.length > 0) {
        if ((parseInt(searchResult.fees) >= parseInt($scope.ranges[0])) && (parseInt(searchResult.fees) <= parseInt($scope.ranges[1])))
            return;
    }
    return searchResult;
}

When I use

filter:priceFilter

it returns random results which fall out of the selected min and max limit.