vendredi 31 mars 2017

How to sort the sequence of checkbox

I have two checkboxes. If I check cb1 first and cb2 next, the ListBox should display the data of the checkboxes in order of checked sequence.

Public Class Form1

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If cb1.Checked = True And cb2.Checked = False Then
      ListBox1.Items.Add(cb1.Text)
      If cb1.Checked = True And cb2.Checked = True Then
        ListBox1.Items.Add(cb1.Text)
      End If
    ElseIf cb2.Checked = True And cb1.Checked = False Then
      ListBox1.Items.Add(cb2.Text)
      If cb2.Checked = True And cb1.Checked = True Then
        ListBox1.Items.Add(cb1.Text)
      End If
    End If
  End Sub
End Class

If only one checkbox is checked it displays the data, but if both are checked there's no data displayed in the list box.

Enter image description here




Add checkbox button

I'm creating list view with checkboxes, and I need in this a button that adds next checkbox in my form app. I know how to add single box, but idk how to make a loop that will helps me to add next checkboxes. Here, I give u a piece of code. At the start I have 24 checkboxes, next must be on 612 px position.

private void btnAdd_Click(object sender, EventArgs e)
    {
         CheckBox box;
         box = new CheckBox();
         box.AutoSize = true;
         box.Location = new Point(30, 612);
         this.Controls.Add(box);
    }




input check box need to be in checked at first in ng2

This below is that i am expecting to be evaluated,but,this input checkbox need to be in ticked (visually) condition when its all loaded. But, as of now, it is not happening. on this code, my functionality working fine, additionally, i need this update on this checkbox in ng2. On loading of all checkboxes need to be in ticked condition(visually, true in technical), if i change the value that should be updated to ngModel.

Any clue, pls?

<input type="checkbox" value="" [(ngModel)]="item['checked']" id="myCheck" (change)="itemRemovelist(item, item['checked'])">




Radio and Checkbox Inputs Not Working With scrollOverflow=true (On Mobile Only)

WHAT I AM USING?

I am using FullPage.js with scrollOverflow.

MY SETTINGS

These are my settings

<script>
$(document).ready(function() {
    $('#fullpage').fullpage({
        //Navigation
        sectionsColor: ['#06C', '#C06', '#930', '#06C'],
        anchors: ['aa', 'bb', 'cc', 'dd'],
        menu: '.menu',
        navigation: true,
        scrollOverflow: false, /* True or False Depending */
        scrollBar: true,
        fixedElements: '.header',
        paddingTop: '3em',
        slidesNavigation: true,
        paddingBottom: '1em'
            });
});
</script>

PROBLEM EXPLANATION

I have a contact form that has radio and checkboxes inputs but those inputs don't work in mobile devices with scrollOverflow equals to true. They work on desktops though.

If I chancge scrollOverflow to false the inputs work on mobile but scrollOverflow does not works which is needed because the contact form is long for mobile.

LIVE EXAMPLES

You can see scrollOverflow=true (enable) on this live example 1 but radio and checkbox inputs don't work on mobile.

  1. http://ift.tt/2npqSdm

On these example 2 I disabled scrollOverflow=false and the radio and checkbox inputs work on mobile but the scrollOverflow don't works which is bad if the contact form is long and I need to scroll.

  1. http://ift.tt/2mUK1aO

Does anyone knows how to fix this?




Jquery chekbox select all except diabled

I have this jsp code as a header to toggle all checkbox:

<th><input name="checkAll" type="checkbox" onClick="toggleCheck(this, this.form.poFulfill);"/></th>

Each row reads the record whether that checkbox will be disabled or not:

<input type="checkbox" name="poFulfill" value='<%=row.poId.toString()%>'
<%=(row.qtyIn.compareTo(row.qtyOut) == 0))?"disabled":""%>>

I want to select all checkbox that is ENABLED only. I read I need to use jquery so I modified my header to:

<th><input id="chkSelectAll" name="checkAll" type="checkbox"/></th>

And added this:

<script type="text/javascript">
$('#chkSelectAll').click(function () {
var checked_status = this.checked;
$('div#item input[type=checkbox]').not(":disabled").prop("checked", checked_status);
});
</script>

Not working and nothing happens when I click checkbox to select all. Any idea?




Android: Implement Select all checkbox in gridview with checkbox and imageview

I want to make custom gallery with image and checkbox, user can select single image by selecting individual checkbox of image and also i have checkall functionality to select all the checkbox in the gridview.

I have implemented ViewHolder class for custom gridview

here is my code:

public class MainActivity extends AppCompatActivity {

private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
CheckBox chkSelectAll;

GridView imagegrid;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    chkSelectAll= (CheckBox) findViewById(R.id.chkSelectAll);
     imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);




    final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    Cursor imagecursor = managedQuery(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
            null, orderBy);
    int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
    this.count = imagecursor.getCount();
    this.thumbnails = new Bitmap[this.count];
    this.arrPath = new String[this.count];
    this.thumbnailsselection = new boolean[this.count];
    for (int i = 0; i < this.count; i++) {
        imagecursor.moveTo`enter code here`Position(i);
        int id = imagecursor.getInt(image_column_index);
        int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
        thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
                getApplicationContext().getContentResolver(), id,
                MediaStore.Images.Thumbnails.MICRO_KIND, null);
        arrPath[i]= imagecursor.getString(dataColumnIndex);
    }
    imageAdapter = new ImageAdapter();
    imageAdapter.notifyDataSetChanged();
    imagegrid.setAdapter(imageAdapter);
   // imagecursor.close();
    findViewById(R.id.chkSelectAll).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           /* ViewHolder vh=new ViewHolder();
            for (int i = 0; i < imagegrid.getCount() ; i++ ){
                View view = imagegrid.getChildAt(i);
                if(view != null) {
                    vh.checkbox = (CheckBox) view.findViewById(R.id.itemCheckBox);
                    vh.checkbox.setChecked(true);
                }
            }*/

           int count = imagegrid.getAdapter().getCount();
            for (int i = 0; i < count; i++) {
                RelativeLayout itemLayout = (RelativeLayout)imagegrid.getChildAt(i); // Find by under LinearLayout

                Log.e("", "onClick: "+itemLayout );
                CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.itemCheckBox);
                checkbox.setChecked(true);
            }



        }
    });
}



public void selectedImage()
{
    final int len = thumbnailsselection.length;
    int cnt = 0;
    String selectImages = "";
    for (int i =0; i<len; i++)
    {
        if (thumbnailsselection[i]){
            cnt++;
            selectImages = selectImages + arrPath[i] + "|";
        }
    }
    if (cnt == 0){
        Toast.makeText(getApplicationContext(),
                "Please select at least one image",
                Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getApplicationContext(),
                "You've selected Total " + cnt + " image(s).",
                Toast.LENGTH_LONG).show();
        Log.d("SelectedImages", selectImages);
    }
}
public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    public ImageAdapter() {
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    public int getCount() {
        return count;
    }

    public Object getItem(int position) {
        return position;
    }

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

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

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(
                    R.layout.galleryitem, null);
            holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
            holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);

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


        holder.checkbox.setId(position);
        holder.imageview.setId(position);
        holder.checkbox.setOnClickListener(new View.OnClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            public void onClick(View v) {
                // TODO Auto-generated method stub
               CheckBox cb = (CheckBox) v;
                int id = cb.getId();
                if (thumbnailsselection[id]){
                    cb.setChecked(false);
                    thumbnailsselection[id] = false;
                } else {
                    cb.setChecked(true);
                    thumbnailsselection[id] = true;
                    selectedImage();

                }
            }
        });
        holder.imageview.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                int id = v.getId();
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.parse("file://" + arrPath[id]), "image/*");
                startActivity(intent);
            }
        });
        holder.imageview.setImageBitmap(thumbnails[position]);
        holder.checkbox.setChecked(thumbnailsselection[position]);
        holder.id = position;

        return convertView;
    }

}
class ViewHolder {
    ImageView imageview;
    CheckBox checkbox;
    int id;
}

}

Gallery_item.xml

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<ImageView
    android:id="@+id/thumbImage"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:src="@mipmap/ic_launcher"
    android:layout_centerInParent="true" />

<CheckBox
    android:id="@+id/itemCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:buttonTint="@android:color/white"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true" />
    </RelativeLayout>

activity_main.xml

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="fill_parent"
xmlns:app="http://ift.tt/GEGVYd"
android:background="@android:color/white"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_top"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="#F4E178">
    <ImageView
        android:id="@+id/backbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"/>
    <CheckBox
        android:id="@+id/chkSelectAll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:buttonTint="@android:color/white"
        app:buttonTint="@android:color/black"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select All"
        android:textColor="#D7793A"
        android:textSize="20dp"
        android:id="@+id/toolbar_title" />
    <ImageView
        android:id="@+id/btnDelete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"/>

</android.support.v7.widget.Toolbar>


<GridView
    android:id="@+id/PhoneImageGrid"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnWidth="80dp"
    android:gravity="center"
    android:horizontalSpacing="5dp"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:verticalSpacing="5dp" />
<Button
    android:id="@+id/selectBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:minWidth="200px"
    android:text="Select" />
  </LinearLayout>

Log cat

03-31 07:36:03.423 25505-25505/dixit.com.multiselectgallery E/AndroidRuntime: FATAL EXCEPTION: main Process: dixit.com.multiselectgallery, PID: 25505 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setChecked(boolean)' on a null object reference at dixit.com.multiselectgallery.MainActivity$1.onClick(MainActivity.java:90) at android.view.View.performClick(View.java:4780) at android.widget.CompoundButton.performClick(CompoundButton.java:120) at android.view.View$PerformClick.run(View.java:19866) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)




CSS: display a long string line-line with checkbox

I have a string with 255 characters (no space) and want to display it inline with a checkbox, not under. I have tried inline; inline-block; ... but it doesn't work. Anyone help?

<div class="item">
    <input type="checkbox" id="a">
    <label for="a">a</label>
</div>
<div class="item">
   <input type="checkbox" id="b">
<!-- 255 characters string here -->
    <label for="b">eyDlDLuT8A8AMTeyHSBXj4BeiWefQc1KWilxVWe7m7Vja1m9eEDc8iJ778jvaR2pCN2PcPcIWexrHehXSPJGqWaiSWfqSZL3AuZfOB0U3hlOCQMFWmqHWsERpWrF5YynmiJnn5mZoUP9TDPjW379O38BuBH9Q5zYlIRWgxAskcFT4DJAejiiIeu78jt1jsUU90RqV499IigZSqluOaJY3sptm0qADxE5M1JmnfEB9a8v7yihlrDq3Yy1MVMofBF</label>
</div>
<div class="item">
    <input type="checkbox" id="c">
    <label for="c">c</label>
</div>




jeudi 30 mars 2017

checkbox $.change is being triggered by itself and looping because it is being modified inside $.change

I have a group of checkboxes that when you click ONE, they should ALL be checked.

When a user clicks one checkbox, it checks all the other checkboxes starting with that class name. What I want is for the user to click a checkbox, and "$(".atpSelections").change" is triggered only once per click.

Here's the code:

        $(".atpSelections").change(function() {
            console.log("CHANGED");

            //Check ALL other checkboxes starting with that class name:
            var className = $(this).attr("class");
            className=className.replace("atpSelections ", "");
            className=className.trim();
            className=className.split("-");

            //Get current checkbox state
            var currentState = $(this).attr("checked");

            //Now loop through all other checkboxes starting 
            //with the same class name and check them:
            $("input[class*='"+className[0]+"-']").each(function(i){
                    //THIS IS TRIGGERING "$(".atpSelections").change"!!
                    if(currentState && currentState=="checked")
                    {
                        $(this).prop('checked', true);
                    }else
                    {
                        $(this).prop('checked', false);
                    }
                });
        });

The Problem

The problem is that when the user clicks one checkbox, the $(".atpSelections").change method gets triggered over and over because $(this).prop('checked', true); triggers $(".atpSelections").change again, and it just goes round and round.

So 1 click to a checkbox triggers 100s "change" events, when I only want it triggered once.

How do I alter the checkbox's state inside $(".atpSelections").change without triggering $(".atpSelections").change again?

Attempts

I tried changing $(".atpSelections").change to $(".atpSelections").click but it had the same issue. I think $(this).prop('checked', true); triggers the click event.




picking up checkbox value and displaying information based on what is checked in php

I am trying to create a system that displays a sport the user might want to play based on what they already play. The system will display the question "What sport do you play?" and give the user a number of options with checkboxes to choose the sports that they already play. When the user clicks the submit button the system will generate an answer based on what they have chosen. For example of the user picks basketball and rugby then the system will display football.

I have started by creating an array to store each value and display them in a checkboxes as shown below.

<?php
                $city = 'city';
                $options = array("Football","Basketball","Rugby", "Hocky", "Golf");
                $box = "";

                if(isset($_REQUEST["$city"])) {
                        $checked=$_REQUEST["$city"];
                }else{
                        $checked=array();
                }
                foreach ($options as $option) {
                        $checkmark=(in_array($option,$Checked))?'checked':'';
$cityAsArray=$city.'[]';

$boxs.=($style=='V')?"<span class='label2' align='right'><b>$option : </b></span>":"<b>$option </b>";
$boxs.="<input type='checkbox' name='$cityAsArray' id='$option' value='$option' $checkmark >";
}

                echo<<<EOF

<form name="Update" method="GET" action="{$_SERVER['PHP_SELF']}">\n


{$boxs}
<br>
<br>
<button type="submit" >Submit Form</button>
</form>
EOF
;

?>

I want to have a function that picks up what has been clicked and displays the right information based on that. I have searched online for tutorials to help with this but I am unable to find any.




How to make checkbox selected during rendering

I have already look and applied lots of the solution methods on web i.e. Check/Uncheck checkbox with javascript? but my problem is make the checkbox to be checked after page load. I use $(window).load(function () and $(document).ready(function () but none of them working. However, if I can set checked property in html of checkbox the problem will be solved. But I cannot set this property via a Javascript variable. I also tried by jQuery but the problem is related to setting this property after rendering of checkbox. Any idea to fix the problem?

<input type="checkbox" class="form-check-input" id="chkAll" >

//Although the checkboz is already rendered at this stage I cannot set it
$(window).load(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});

and

//As the checkbox is not rendering during page load this method is useless
$(document).ready(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});




How show-hide columns from table with checkbox?

I want to show or hide a column in my table using a checkbox. i try to use datatables plug-in but it doesnt'work. Is there a simple solution with jquery? I found a useful code (http://ift.tt/2nCE0hW) but I don't know how assign a class to "th" to use it. Do you know another solutions?

<?php
$dbLink = mysqli_connect('localhost', 'root', '');
mysqli_select_db($dbLink, 'projects');
$sql = "SELECT relation.id_pers, relation.enroll_year, course.course_description, course_type.type_description FROM relation JOIN course ON relation.id_course=course.id_course JOIN course_type ON course_type.id_type=course_type.id_type LIMIT 15";
$result = mysqli_query($dbLink, $sql) or die(mysql_error());
// Print the column names as the headers of a table
echo "<table id='example'><thead>";
for($i = 0; $i < mysqli_num_fields($result); $i++) {
    $field_info = mysqli_fetch_field($result);
    echo "<th>{$field_info->name}</th>";
    }
 echo "</thead>";
// Print the data
while($row = mysqli_fetch_row($result)) {
    echo "<tr>";
    foreach($row as $_column) {
        echo "<td>{$_column}</td>";
    }
    echo "</tr>";
}
echo "</table>";
?>

And this is my checkbox :

    <section>
   <ul>
      <li>
         <input type="checkbox" name="check[]" id="option"><label for="option">Matricola</label>
         <ul>
            <li><label class="suboption"><input type="checkbox" id="id_stu" class="subOption"> ID studente</label></li>
            <li><label class="suboption"><input type="checkbox" class="subOption"> corso di studi</label></li>
            <li><label class="suboption"><input type="checkbox" class="subOption"> anno di iscrizione</label></li>
         </ul>
      </li>
   </ul>
</section>




Multiple checkboxes to variable logic

I am looking to create a simple page using HTML and (probably) PHP or JQuery. The page should allow for multiple checkbox selection, and give a variable a value based on which boxes are checked. This can be on submit or can render live on the page.

i.e.
Checkbox 1
Checkbox 2
Checkbox 3

If checkbox 1 is checked, variable = X
If checkbox 1 & 2 are checked, variable = Y
If no checkboxes are checked, variable = Z

What is the best way to approach doing this?




Via Javascript only, check a checkboxlist to see if each item is selected, and set focus to the checkboxlist

I have a checkboxlist named "cblNSGONF". I tried using this looping to set focus that these two items under checkboxlist are checked:

  • If not, an error would occur and set focus on the checkbox list.
  • If all are checked, set focus on the next checkboxlist named "cblNSGONF" with just one item.

Why does this not work. See code in javascript:

   var checkboxlist1 = document.getElementsByName("cblNSGONF");
   var ischecked5 = false;
   for (var i = 0, len = checkboxlist1.Items.Count-1; i < len; i++) {
           if (checkboxlist1.item[i].selected = false) {
                    alert('Please check both checkboxes for NSGO NF Only Certification Only');
                    document.getElementById('cblNSGONF').disabled = false
                    document.getElementById('cbCertify').removeAttribute("checked");
                    document.getElementById('btnSubmit').disabled = true;
                    document.form1.cblNSGONF_0.focus();
                    document.getElementById('lblNSGONFCheckboxes').style.display = "inherit";
                    return;
                    ischecked5 = true;
                    //var cblNSGONFValue = checkboxlist1[i].value;
                    break;
                }
            }

            alert('This is ischecked5 value: ' + ischecked5+ '');

            if (ischecked5 = false) {
                alert('Please check both checkboxes for NSGO NF Only Certification Only');
                document.getElementById('cblNSGONF').disabled = false
                document.getElementById('cbCertify').removeAttribute("checked");
                document.getElementById('btnSubmit').disabled = true;
                document.form1.cblNSGONF_0.focus();
                document.getElementById('lblNSGONFCheckboxes').style.display = "inherit";                                    
                return;
            }

The alert is always getting evaluated to ischecked5 equal false. Why?




mercredi 29 mars 2017

How to count checked checkbox with Javascript?

I would like to count the checkboxes that are checked and display the count in the Div.

Here is my HTML :

<form name="liste_figurine" method="post">

<input type="checkbox" id="radio-1" class="z" name="chck1[]" onclick="updateCount()" />
<input type="checkbox" id="radio-2" class="z" name="chck2[]" onclick="updateCount()" />

</form>

<div id="y"></div>

Here is my JS :

function updateCount {
    var x = $(".z:checked").size();
    document.getElementById("y").innerHTML = x;
};

Here is an exemple : http://ift.tt/2oA3PN4

Sorry, I'm not really used to JS... What is wrong with my code ?




how to bing checkboxes in ember with a list

I have a model where I have a list of all countries as below -

[{"code":"US", "name":"USA"}]

selected counties will be pass on as a list like below -

["US", "CA"]

my template has a list of checkboxes like below -


     
     
       
        <label class="checkbox-inline"></label>
    


the code above doesn't work as intended and I am trying to figure out how to configure the checkbox to achieve what I need. Any ideas?




Sum columns from database using checkbox

I am new to php. I have inserted only a single value in two columns of database. I am trying to add them both using checkbox. Forexample. There is a column with name "englishprice" with only one value 20, and another column "mathprice" with only value 10. I want to sum them using checkbox, Like if i only check englishprice then it shows its price, if i check both then it sums both.




Gridview, Autogenerated Column, Checkbox Column Editable

I have a gridview binded to a datasource.

 <asp:GridView ID="DocumentReviewGrid" runat="server" AllowPaging="True" AllowSorting="True"
                    EnableModelValidation="True" Width="100%" BorderStyle="None" 
                    CssClass="docnav_data" BorderWidth="1px" GridLines="None" DataSourceID="DocumentReviewDataSource"
                    HorizontalAlign="Left" OnRowDataBound="DocumentReviewGrid_RowDataBound" 
                    OnRowCreated="DocumentReviewGrid_RowCreated" CellSpacing="5"
                    PageSize="20" OnPageIndexChanged="DocumentReviewGrid_PageIndexChanged">
                    <AlternatingRowStyle BackColor="#EBF2F9" BorderStyle="None" />
                    <FooterStyle HorizontalAlign="Left" />
                    <HeaderStyle BackColor="#E7E7E7" HorizontalAlign="Left" />
                    <PagerSettings Mode="NumericFirstLast" Position="Top" PageButtonCount="4" />
                    <PagerStyle HorizontalAlign="Center" />                       
                </asp:GridView>

enter image description here

As you can see Autogenerated Column is set to true, and it must be kept like that. One of the column is a SQL bit value, so it's represented as checkbox. I would like to be able to edit the checkbox column only, without using "AutoGenerateEditButton" property. I would just like to:

  • be able to check/uncheck the checkbox (I am stuck here)
  • performin a single update using an external button



Disabling remaining checkboxes after 2 have been selected in android studio

I'm working in Android Studio and I have four checkboxes for a user question. However, only two can be selected. After 2 are checked, the remaining checkboxes should disable.

package com.example.android.tester;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;

public class MainActivity extends Activity {

    private CheckBox chkIos, chkAndroid, chkWindows;

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

        addListenerOnChkIos();
        addListenerOnChkAndroid();
        addListenerOnChkWindows();
    }

    int count = 0;
    public void addListenerOnChkIos() {

        chkIos = (CheckBox) findViewById(R.id.chkIos);

        chkIos.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //is chkIos checked?
               if (count == 2) {
                    chkIos.setEnabled(false);
                } else
                    chkIos.setEnabled(true);
                    count++;

            }
        });

    }

    public void addListenerOnChkAndroid() {

    chkAndroid = (CheckBox) findViewById(R.id.chkAndroid);

    chkAndroid.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //is chkAndroid checked?
            if (count == 2) {
                chkAndroid.setEnabled(false);
            } else
                chkAndroid.setEnabled(true);
            count++;

        }
    });

}

public void addListenerOnChkWindows() {

    chkWindows = (CheckBox) findViewById(R.id.chkWindows);

    chkWindows.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //is chkWindows checked?
            if (count == 2) {
                chkWindows.setEnabled(false);
            } else
                chkWindows.setEnabled(true);
            count++;

        }
    });

}
}

This is code mostly from a Mkyong tutorial that I've been experimenting with. If I run this it allows all three to be checked and then only after I uncheck one, does it disable. Any help is appreciated.

Here's the xml and strings file if anyone wants to try it out

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

<CheckBox
    android:id="@+id/chkIos"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/chk_ios" />

<CheckBox
    android:id="@+id/chkAndroid"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/chk_android"
    android:checked="true" />

<CheckBox
    android:id="@+id/chkWindows"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/chk_windows" />

<Button
    android:id="@+id/btnDisplay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/btn_display" />

</LinearLayout>

Strings:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, MyAndroidAppActivity!</string>
<string name="app_name">MyAndroidApp</string>
<string name="chk_ios">IPhone</string>
<string name="chk_android">Android</string>
<string name="chk_windows">Windows Mobile</string>
<string name="btn_display">Display</string>
</resources>




Align Checkbox and its label

Am working on Oracle CPQ tool,

Where am using checkbox, which is created as attribute.

On UI am getting

enter image description here

And in browser source am getting this HTML code below _

<label class="form-label" for="chkmembershipFeePayment_t" style="width: 100px">
<span style="padding-right: 5px">Membership Fee</span>
</label>
<div class="form-element field-wrapper" id="field_wrapper_1_chkmembershipFeePayment_t" style="padding-left:100px">
<div class="boolean-wrapper field" message="">
    <div class="boolean-wrapper-inner">
        <input value="false" class=" form-input  cm-attr-value " name="chkmembershipFeePayment_t" onclick="if (this.checked) { this.value='true'; } else { this.value='false'; }" data-is-boolean="true" type="checkbox">
    </div>
    <input value="true" name="_boolean_present_chkmembershipFeePayment_t" type="hidden">
</div>
<div id="msg_1_chkmembershipFeePayment_t" class="error-hover" data-action-message="" message=""></div>

My question is , I want to display checkbox before label(Membership Fee) using CSS or JS any. (I can't use html in CPQ tool attribute).

So any way to do that?




Disable button until checkbox ticked

Apologies if this has already been asked, i have found it difficult to use the answers I have found to use in my code.

Basically, I have a "receive" button, that when the user clicks, will receive an email. But, I want a tick box checked in order for the button to become clickable. I have a code that kind of works, but when the page first loads, the "Receive" button is already clickable. However, when I click the tick box then unclick it, it disables the button.

             <td>
                                <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />
            <td>
            <p> I agree to the <a href="terms.html" target="_blank">Terms & Conditions</a></p>
            </td>
                            </td>
                          </tr>
                            <td class="label1"></td>
                            <td align="right">
                                <button type="submit" class="btn btn1" name="terms" id="terms">Receive</i></button>
                            </td>




Multiple select option text standing under the checkbox in materialize.css

In the example you see below, the text (Faculty not selected) stands under the checkbox, i didn't get any special features when i checked the attributes from style palette. Normally text should be near the checkbox. Any idea about the problem?

enter image description here

<div class="container">
    <div class="row">
      <form class="col s12">
          <div class="row mt50">
            <div class="input-field col s3">
                <select class="validate faculty" name="faculty" id="faculty" onchange="getCourse();">
                    <option value="">Choose</option>
                    <option value="FEng">Faculty of Engineering</option>
                    <option value="FMed">Faculty of Medicine</option>
                    <option value="FSci">Faculty of Science</option>
                </select>
                <label for="faculty">Faculty</label>
              </div>
              <div class="input-field col s4">
                <select name="course" id="course" multiple>
                    <option value="" disabled>Faculty not selected</option>
                <select/>
                <label for="course">Course</label>
              </div>
          </div>
      </form>
    </div>
</div>




change all checkboxes in one table-row

I want to uncheck all checkboxes that are in one table row. I have this HTML code :

<tr id="unlosta_line_1">
     <td>
        <input id="unlosta_prop_id_1" name="unlosta_prop_id[1]" value="1"  checked="checked" type="checkbox">
Feld 1
     </td>

     <td>
        <input id="unlosta_prop_id_2" name="unlosta_prop_id[2]" value="2"  type="checkbox">
Feld 2
     </td>

     <td>
        <input id="unlosta_prop_id_3" name="unlosta_prop_id[3]" value="3"  type="checkbox">
Feld 3
     </td>
     <td>...and so on
     <td>
</tr>

What I have tried at now is this jquery code:

$("tr#unlosta_line_1").children("td").each(function(i) { $(i).prop("checked", false) } )




Checkboxes don't stay checked after pagination

Whenever I check a checkbox on a listing page, save it then go to page eg 2 (using pagination) and check something there and save it the checkbox on my first page is unchecked. I thought about using AJAX to save checked checkboxes to grails session but don't know how to do that - I'm beginner with JS and using views. Could someone help me out? Here is the part with listing all companies and checkboxes in my gsp:

 <g:form name="company-list-form" action="listCompany">

    <div>
        <g:textField id="search-field" name="query" value="${params.query}"/>

        <span>
            <g:checkBox id="only-blockades-box" name="onlyBlockades" class="submit-on-change" value="${params.onlyBlockades}" title="Pokaż tylko blokady"/>
            <label for="only-blockades-box">Tylko blokady</label>
        </span>

        <g:actionSubmit value="${message(code: 'default.buttons.search', default: 'Szukaj')}" action="listCompany" class="button_orange"/>
        <g:link action="listCompany" class="button_gray"><g:message code="default.buttons.clean" default="Wyczyść"/></g:link>
    </div>

    <div class="padding-top">
        <table class="table_td company-list-table">
            <tbody>
            <tr class="gray2">
                <th class="first">Id</th>
                <th style="max-width: 100px;">Nazwa</th>
                <th>Id Kontrahenta</th>
                <th title="Dostęp do TPO">TPO</th>
                <th style="width: 20px;" title="Dostawa bezpośrednio do magazynu">Dostawa bezpośrednio</th>
                <th style="width: 20px;" title="Możliwość potwierdzania zamówień">Potwierdzanie zamówień</th>
                <th style="width: 20px;" title="Możliwość importowania awizacji z XLS">Import z&nbsp;Excel</th>
                <th style="width: 20px;" title="Możliwość awizowania zamówionych indeksów">Awizacja zam. indeksów</th>
                <th style="width: 20px;" title="Możliwość awizowania tygodniowego">Awizacja tyg.</th>
                <th style="width: 20px;" title="Dostęp jedynie do awizowania tygodniowego">Tylko awizacja tyg.</th>
                <th title="Limit AGD przypadający na każdą kratkę okna prywatnego">AGD</th>
                <th title="Limit rowerów przypadający na każdą kratkę okna prywatnego">Rowery</th>
                <th>Blokady</th>
                <th class="is-blocked-th">Zablokowany?</th>
            </tr>
            <g:each in="${companyInstanceList}" var="company" status="i">
                <tr class="${(i % 2) == 0 ? 'even' : 'odd'} table_td_gray2 ${i + 1 == companyInstanceList?.size() ? 'last' : ''}">
                    <td class="first" style="text-decoration: underline;">
                        <g:link action="editCompany" id="${company?.id}">${company?.id}</g:link>
                    </td>
                    <td>
                        ${company?.name}
                    </td>
                    <td>
                        ${company?.idKontrahenta}
                    </td>
                    <td>
                        <g:checkBox name="tpoAccess.${company?.id}" id="tpo-access-${company?.id}"
                                    checked="${company?.tpoAccess}"/>
                    </td>
                    <td>
                        <g:checkBox name="directDeliveryAvailable.${company?.id}"
                                    id="direct-delivery-available-${company?.id}"
                                    checked="${company?.directDeliveryAvailable}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessToOrderConfirmation.${company?.id}"
                                    id="access-to-order-confirmation-${company?.id}"
                                    checked="${company?.accessToOrderConfirmation}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessToXlsImport.${company?.id}"
                                    id="access-to-xls-import-${company?.id}"
                                    checked="${company?.accessToXlsImport}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessToOrderedProductsAvisation.${company?.id}"
                                    id="access-to-ordered-products-confirmation-${company?.id}"
                                    checked="${company?.accessToOrderedProductsAvisation}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessToLimitedAvisation.${company?.id}"
                                    id="access-to-limited-avisation-${company?.id}"
                                    checked="${company?.accessToLimitedAvisation}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessOnlyToLimitedAvisation.${company?.id}"
                                    id="access-only-to-limited-avisation-${company?.id}"
                                    checked="${company?.accessOnlyToLimitedAvisation}"/>
                    </td>
                    <td>
                        <input type="text" name="agdPrivateWindowLimit.${company?.id}"
                               value="${company?.agdPrivateWindowLimit}"
                               class="shortText" id="agd-private-window-limit-${company?.id}"
                               onchange="validateLimits('agdPrivateWindowLimit.${company?.id}')">
                    </td>
                    <td>
                        <input type="text" name="bicyclePrivateWindowLimit.${company?.id}"
                               value="${company?.bicyclePrivateWindowLimit}"
                               class="shortText" id="bicycle-private-window-limit-${company?.id}"
                               onchange="validateLimits('bicyclePrivateWindowLimit.${company.id}')">
                    </td>
                    <td>
                        <g:link class="button_gray" controller="productGroup" action="list" params="[companyId: company?.id, query: params.query ?: '']">
                            Blokady
                        </g:link>
                    </td>
                    <td>
                        <g:if test="${company?.findBlockades()}">
                            <span title="Dostawca ma aktywne blokady grup towarowych." class="bold large">
                                &#x2713;
                            </span>
                        </g:if>
                    </td>
                </tr>
            </g:each>
            </tbody>
        </table>
    </div>

    <div class="paginateButtons">
        <g:paginate controller="company" action="listCompany" total="${companyInstanceTotal}"
                    params="[query: params.query ?: '']"/>
    </div>

    <div style="float:right;">
        <g:link action="createCompany" class="button_orange">
            <g:message code="default.button.create.label" default="Utwórz"/>
        </g:link>
        <g:actionSubmit action="updateCompanies" name="companyListSubmit" class="button_orange" value="Zapisz"/>
    </div>

</g:form>

Here is my javascript file associated with that view:

    function validateLimits(name) {
    document.getElementsByName(name)[0].value = document.getElementsByName(name)[0].value.replace(/[A-Za-z!@#$%^&*" "]/g, "");
    var quantity = document.getElementsByName(name)[0].value;
    var toBeAvised = 9999;
    if (quantity.indexOf(',') > -1 || quantity.indexOf('.') > -1 || /*quantity == "" ||*/ isNaN(quantity)) {
        alert("Limit musi być liczbą całkowitą");
        document.getElementsByName(name)[0].value = '';
    } else if (parseInt(quantity) > toBeAvised) {
        alert("Podana liczba jest większa niż maksymalny limit równy " +toBeAvised + ".");
        document.getElementsByName(name)[0].value = '';
    } else if (parseInt(quantity) < 0) {
        alert("Limit musi być liczbą dodatnią!");
        document.getElementsByName(name)[0].value = '';
    }
}

And here is controller method (listCompany):

 def listCompany(Integer max) {
        Person person = Person.read(springSecurityService.principal.id)
        Company comp = person?.company

        params.max = Math.min(max ?: 25, 100)
        params.offset = params.offset ?: 0
        params.readOnly = true

        String q = (params.query as String)?.toLowerCase() ?: ""

        def query = Company.where {
            id != comp?.id
            name =~ "%$q%" || idKontrahenta as String =~ "%$q%"
            if (params.onlyBlockades == "on") {
                id in ProductGroupBlockade.findAllByCompanyIsNotNullAndEnabled(true)*.companyId
            }
        }
        List<Company> companyInstanceList = query.list([max: params.int("max"), offset: params.int("offset"), sort: "name"])
        Integer count = query.count()
        if (flash.message) {
            params.errors = flash.message
        }
        [companyInstanceList: companyInstanceList, companyInstanceTotal: count, companySaved: params.companySaved, errors: params.errors]
    }

How I could fix that so my checkboxes stay checked after saving? Right now they become unchecked whenever I go to next page and save some checkboxes there.




mardi 28 mars 2017

How can I get the checked status of a checkbox

I have a gridview parameter in my asp.net program as follows:

Name: row.Cells[5].Controls[0]

Value: (Text="" Checked=true)

type: System.Web.UI.WebControls.CheckBox

How can I get the Checked status of such parameter?




tkinter checkbox **with command attached**

I would like some help with something simple: A tkinter checkbox that does have a command attached <--this simple example is always mentioned but never shown in tutorials on the web.

I have:

from tkinter import *

def activateMotors(active):
    scale.config(state=active)


root = Tk()
root.wm_title('Servo Control')
motorsOn= IntVar()
motorsCheck=Checkbutton(root,text="Motors ON(checked)/OFF(unchecked)", variable=motorsOn, command=activateMotors)
motorsCheck.pack()
scale = Scale(root, from_=0, to=180, 
              orient=HORIZONTAL,label="Motor #",state=DISABLED)
scale.pack()
root.mainloop()

This does not work. Sure the window comes up but when I click on the checkbox I get "TypeError activateMotors() missing 1 required positional argument 'active' "

Can anybody correct this so that we can have one operational checkbox example with commands?




JQuery get checkbox id

I'm trying to get an id of a checkbox. There are several checkboxes on a page that have ids like: channel_left_restream_ids_42, channel_left_restream_ids_44, etc. I need to handle an event when one of those checked and get an id of the checked.

So for checkbox with code <input type="checkbox" value="42" checked="checked" name="channel[left_restream_ids][]" id="channel_left_restream_ids_42"> and coffescript like this:

$("input[id*=channel_left_restream_ids]").change (e) =>
  alert($(this).attr("id"))

I can't get it work. It says undefined. I've tried a lot of alternatives, none worked. Where am I doing a mistake?

JSFiddle is here




Check if various checkboxes that have being created programmatically are checked when you click a button in android

My question is: How I can check if the checkboxes are checked and how can I get its id or text in a onclick event? I have done it whit RadioGroup, but RadioGroup only let me check 1 RadioButton, and in this case I need to check more than one, but if Im wrong and there is a way to do it with RadioGroup it should work for me. Thanks for the help Here is the code where I create the checkboxes programmatically:

protected void onCreate(Bundle savedInstanceState) {

    LinearLayout lg = (LinearLayout) findViewById(R.id.lg);
    Button botonenv = (Button) findViewById(R.id.botonenv);


    try{
        myJson = new JSONObject(data);

        JSONArray Solutions = myJson.getJSONArray("solutions");


        for (int i = 0; i < Solutions.length(); i++) {

            JSONObject JSonSol = Solutions.getJSONObject(i);
            final String idSt = JSonSol.getString("id");
            final String name = JSonSol.getString("name");
            String resp = name.toUpperCase();


            CheckBox cb1 = new CheckBox(this);

            cb1.setText(resp);

            LinearLayout.LayoutParams llg = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            llg.setMargins(0, 30, 0, 0);


            cb1.setTextSize(15);
            cb1.setTextColor(Color.parseColor("#FF000000"));


            lg.addView(cb1);


            int id =Integer.parseInt(idSt);
            cb1.setId(id);


        }



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

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

           //HERE I MUST NOW WHAT CHECKBOXES ARE CHECKED AND THEIR IDS

        ..............
        }           
    });


}




IE11 and Edge don't get value of checkbox when submitting form

This returns null on IE11 and MS Edge, but returns 'yes' on Chrome and Firefox:

$insuranceChecked = Mage::app()->getRequest()->getPost('insurance');
var_dump($insuranceChecked); die;

This is the checkbox input field:

<input id="insurance" type="checkbox" name="insurance" value="yes" form="product_addtocart_form">
<label for="insurance"></label>

Any idea why? I really need to fix this ASAP.




IE Checkbox looking different from Chrome

I am facing some Issue on making my web page Cross Browser Compatible.Issue I am facing is my Check box is looking significantly different in IE 11 from Checkbox in Chrome. I think there is some Issue in webkit Layout Engine,but how to make that work in IE 11

Any pointers will be helpful. Thanks in Advance.




How does one enter a 'checkbox' character on a pdf generated by report4pdf?

So I am working on generating PDFs using the report4PDF package(bob nemec) from the VisualWorks 8.1 software from Cincom. I am doing everything in 'smalltalk'.

However right now, the issue I am facing is that I can't get a checkbox character to show up on the PDF.

So my code would go along like this:

pdfDocument := Report4PDF.R4PReport new.
exporter := SAGETEAPDFDataExporter onDocument: pdfDocument.
exporter currentText text string:' Available'.
"Followed by relevant code to save PDF"

But what shows up on my PDF is basically ' Available'. A space appears instead of the checkbox symbol. I even tried using dingbats codes(e.g: #9744 ). Works with the copyright, alpha, gamma symbols. Not with the checkbox symbol.

I tried updating my VisualWorks image from the public repository using the report4pdf, pdf development and fonts development packages. Ran into some issues which I wont mention since it will derail us from the topic.

Thanks in Advance!




Google map markers not removing upon checkbox action

I was having some problem trying to filter the list fetched from database upon checkbox action and plot/clear markers onto map. Here is my checkbox declaration in HTML:

<div class="">
     <label>
          <input type="checkbox" class="js-switch" name="tags" value="3" onchange="filterList()" unchecked/> MRT Incidents
     </label>
</div>

When checkbox onchange, I am filtering the list fetched from database:

        function filterList(){
        var tags = document.getElementsByName('tags');
        var i = 0;
        

    addMarker(filteredList);
    }

Then in my addMarker with filteredList parameter:

function addMarker(filteredList){ 
        for(var i = 0; i < filteredList.length; i++){
        myLatLng = {lat: parseFloat(filteredList[i].lat), lng: parseFloat(filteredList[i].lng) };

        marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            clickable: true
        });
}

My plotting works weird as well. When I try to check multiple box, let's say I checked the first one, it plotted out. Then I proceed to check the second, it does not plot out but only plot out after I uncheck the first one.

When I try to uncheck the checkbox, the markers on the map are not removed. Instead, it just stay there forever and stacked more and more when I check/uncheck a few times.

Why is it so? Thanks in advance!




How can I make a js function recognize a clicked or empty checkbox?

I'm modifiying an existing form.

You can launch a task block with several fields, and if these are all empty, you can remove the block again. Most of them are required, to submit as data complete. If not complete, you can save Work in Process (sic! I'd have preferred Work in Progress...)

For the code to recognize empty fields, it seems that most of them have value="". When completed, the system seems to to recognize that they are not empty.

But the Checkbox I want to use causes problems.

If I don't set value="", it's not recognized as empty, and I can't remove the block.

If I set value="" , it's not recognizing an entered checkmark, and I can't submit for Data Complete.

I thought that onClick="...." and defining a way to set value="true" would be a way forward, but haven't found any example while searching, and being quite the beginner, I haven't learned it all yet.

the checkbox (to be renumbered up to id 050):

<label for="completed_001">Task Completed<em class="labelrequired">*</em></label>
<input type="checkbox" id="completed_001" name="completed_001" alt="Task Completed 001" title="Task Completed 001" value="" class="validate['required']">

the function: (where the last row concerns the checkbox)

function isEmptyAction(nr) {

    var pad = "000";
    var nr = (pad+nr).slice(-pad.length);

    return  document.getElementById('taskdescription' + nr).value == '' &&
            document.getElementById('TaskOwner' + nr).value == '' &&
            document.getElementById('taskduedate' + nr + '_date').value == '' &&
            document.getElementById('documentid' + nr).value == '' &&
            document.getElementById('resultsandcomments' + nr).value == '' &&
            document.getElementById('completed_' + nr).value == '';  
}

= = = = = UPDATE = = = =

1) thanks for the edit improvement, fellow user dmorrow!

2) Thanks for the tips and suggestions, I got it to work eventually!

I removed the value="" from the checkbox code in the html. This allows the entered checkmark to be recognized, when required for sumbmitting Data Complete.

I used document.getElementById('completed_' + nr).checked == false; in the function for checking that all fields are empty. This allows removing the task block when empty.

Thanks again! You made me a happy beginner!




Change color of checkbox field when checked

I have a check box field with box label colored in green. I need to change the color of the boxlabel (say: yellow) when a user checks the checkbox. i tried validating the checkbox, but it doesnt work. Any suggestions?

xtype :  'checkbox',
id: 'checkbox1',
name : 'checkbox',
style: 'background-color : #BCF5A9',
boxLabel: 'Mycheckbox'
//I tried the below handler function. but it doesnt work
handler: function (checkbox, checked) {
            if (checked) {
                style : 'background-color: #ddd';
            }
}




Why my code don't count row in table when using filter checkbox

I have table with checkbox filter, when run code the count run good, but when i checkbox to filter it don't count any, my html:

<table class="checkcontainer">
  <tr>
    <td>
      <input type='checkbox' name='filter' id="One" checked="" value="One" onchange="chct()"/> One
    </td>
    <td>
      <input type='checkbox' name='filter' id="Two" checked="" value="Two" /> Two
    </td>
    <td>
      <input type='checkbox' name='filter' id="Three" checked="" value="Three" /> Three
    </td>
  </tr>
</table>

<table class="datatbl" border=1 >
  <tr>
    <th>No.</th>
    <th>Content</th>
    <th>Type</th>
  </tr>
  <tbody id="aaa">
  <tr data-rowtype="One">
    <td>1</td>
    <td>this is first row</td>
    <td>One</td>
  </tr>
  <tr data-rowtype="Two">
    <td>2</td>
    <td>this is second row</td>
    <td>Two</td>
  </tr>
  <tr data-rowtype="Three">
    <td>3</td>
    <td>this is third row</td>
    <td>Three</td>
  </tr>
  <tr data-rowtype="One">
    <td>4</td>
    <td>this is fourth row</td>
    <td>One</td>
  </tr>
  <tr data-rowtype="Two">
    <td>5</td>
    <td>this is fifth row</td>
    <td>Two</td>
  </tr>
  <tr data-rowtype="Three">
    <td>6</td>
    <td>this is sixth row</td>
    <td>Three</td>
  </tr>
</tbody>

JS:

window.console.clear();
$('.checkcontainer').on('change', 'input[type="checkbox"]', function() {
  var cbs = $('.checkcontainer').find('input[type="checkbox"]');
  var all_checked_types = [];
  cbs.each(function() {
    var mycheckbox = $(this);
    $('.datatbl tr').filter(function() {
        return $(this).data('rowtype') == mycheckbox.val();
    }).toggle(mycheckbox[0].checked);
  });
});
$("#total").text($("#aaa tr").length);
function chct() {  
$("#total").text($("#aaa tr").length);
}

When i checked checkbox, but function to count row in table not run

How i can count row in table when using filter checkbox ?

Thank you

Code jsfiddle




select checkbox and select dropdown then disable button in js?

//table //class=flat Job ID Customer Name Zone Delivery Date Allocate to Driver ${taskMasterList.job_id} ${taskMasterList.customer_name} ${taskMasterList.zone_name} ${taskMasterList.deliveryDate} //my dropdown id="setpp" //save button id="zonehide1" Save




lundi 27 mars 2017

isSelected() Checkbox error

I'm making some kind of calculating program where user can input the number of drinks that they want to order and a button will calculate the amount of money they need to pay. If they checked the delivery box, there will be an addition of $30 for delivery cost. i'm using isSelected to check if they box if ticked or not but it's not working. the error that i get is "the method isSelected() is undefined for the type Checkbox".

import java.awt.*;
import java.awt.event.*;
public class hwextend{

static Frame frm = new Frame("Action Event");
static Checkbox ckb1 = new Checkbox("Delivery");
static Button btn = new Button("Calculate");
static TextField textfield1 = new TextField();
static TextField textfield2 = new TextField();
static TextField textfield3 = new TextField();
static TextField textfield4 = new TextField();
static TextField textfield5 = new TextField();

public static void main(String[] args) {
    // TODO Auto-generated method stub



    GridLayout grid = new GridLayout (7,3);
    btn.addActionListener(new ActListener());
    frm.setLayout(grid);
    frm.setSize(400,200);
    frm.setBackground(Color.pink);


    Label lab1 = new Label ("Tea Series");
    Font font1 = new Font(null,Font.BOLD,12);
    lab1.setFont(font1);
    frm.add(lab1);
    frm.add(new Label(""));
    frm.add(new Label(""));


    frm.add(new Label("Black Tea"));
    frm.add(new Label("$70"));
    frm.add(textfield1);


    frm.add(new Label("Green Tea"));
    frm.add(new Label("$70"));
    frm.add(textfield2);

    Label lab2 = new Label ("Special Flavor Series");
    lab2.setFont(font1);
    frm.add(lab2);
    frm.add(new Label(""));
    frm.add(new Label(""));


    frm.add(new Label("Alpine Tea"));
    frm.add(new Label("$80"));
    frm.add(textfield3);


    frm.add(new Label("Stewed Oolong Tea"));
    frm.add(new Label("$80"));
    frm.add(textfield4);


    frm.add(btn);
    frm.add(ckb1);


    frm.add(textfield5);
    frm.addWindowListener(new WindowAdapter()
    { 
          public void windowClosing (WindowEvent Event) {
          System.exit (0);
         } 
        } 
        );


    frm.setVisible(true);
}


static class ActListener implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        int a = Integer.parseInt(textfield1.getText().toString());
        int b = Integer.parseInt(textfield2.getText().toString());
        int c = Integer.parseInt(textfield3.getText().toString());
        int d = Integer.parseInt(textfield4.getText().toString());

        if (ckb1).isSelected()){
            textfield5.setText(String.valueOf((a+b)*70+(c+b)*80)+30);
        }
        else {
        textfield5.setText(String.valueOf((a+b)*70+(c+b)*80));
        }
            }


}

}




AngularJS mg-repeat items with checkbox preventing default on cancelled confirmation

I am using angular (first version) and I having trouble trying to accomplish a task. I have a list of item that I retrieve from the server DB. I am listing those items in a HTML table. There's a Boolean field that I want to update dynamically when the user check or uncheck a checkbox. The problem is during the confirmation. When I cancel the confirmation the check if still retaining its state (check/uncheck) and not going back to its previous state. I tried using "preventDefault", it didn't work. I tried "refreshing" the item array so the view might refresh the data, it didn't work. Here's a fiddle with a representation of what I have: Fiddle

<div ng-app ng-controller="demoController">
  <h3>
    <span class="status"></span>
  </h3>
  <h2>
    Movies i've seen
  </h2>
  <table>
    <tr>
      <th>Name</th>
      <th>Have I seen it?</th>
    </tr>
    <tbody>
      <tr ng-repeat="movie in movies">
        <td> </td>
        <td style="text-align: center">
          <input value=" " type="checkbox" ng-checked="movie.seen" ng-click="confirmSeen(this, $index)" /> </td>
      </tr>
    </tbody>
  </table>
</div>



 function demoController($scope) {
  $scope.status = "AngularJS is up";
  $scope.confirmSeen = function(e, idx) {
    var movie = $scope.movies[idx];
    if (movie !== undefined) {
        var msg = "";
      if(movie.seen) {
        msg = "Are you sure you want to mark " + movie.name + " as unseen?";
      } else {
        msg = "Are you sure you want to mark " + movie.name + " as seen?";
      }

      if (confirm(msg)) {
        movie.seen = !movie.seen;
        $scope.movies.splice(idx, 1, movie);
      } else {
        $scope.movies.splice(idx, 1, movie);
        e.stopImmediatePropagation();
        e.preventDefault();
      }
    } else {
      e.stopImmediatePropagation();
      e.preventDefault();
    }
  }
  $scope.movies = [{
    name: "Conan",
    seen: false
  }, {
    name: "Scarface",
    seen: true
  }, {
    name: "GhostBuster",
    seen: false
  }, {
    name: "The Shawshank Redemption",
    seen: true
  }, {
    name: "Goodfellas",
    seen: true
  }, {
    name: "Life",
    seen: false
  }];
}




I created a registration page and now I want to confirm all information including checkbox

I creating a registration page with details linked to MySQL data. And, I want to show just the rows which are checked in checkboxes on the next page.

I am not able to figure out how to use checkbox output value on next page to toggle

Style = "display : none / block ; "




php/html input checkbox's

Not that sure if this question has been answered somewhere.. have searched for it and found some stuff about it.. but sincerelly don't really understand the answers ive seen and probably am making a major confusion since im not that experienced on working with these languages..

The thing is that i have a group of 5 checkbox's which i want to post in a binary output for example: [0,0,1,1,0].

So far i've managed this by applying the hidden input solution (which i described in a more static way.. since i have a lot of things coming from the db, and other things that dont make sence to explain for this problem.. i think)

$checkychecky = [1,0,1,0,0];
<input type="hidden" name="'.$row_perguntas[0].'[]" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value"'.$checked = ($checkychecky[0] == 1 ? "checked=\"checked\" " : "")/>'.$questionV[1].'

row_perguntas-> comes from the db which gives me the display name

checkychecky -> temp var which stores the values present in the values array [1,0,1,0,0]

questionV -> db label content

which is working just fine.. the problem is when i go forward to another form, and then come back to this form, i get the right arrray values, managed to place the visible checkbox checked, but aint sure on what to do with the hidden field.. since tecnically it isnt set, i dont press the checkbox.. so the onclick doesnt fire.. and when i advance to the next form again i end submiting [0,0,0,0,0]

How should i address this stituation? have tryed to use the.. checkychecky on the hidden input:

<input type="hidden" name="'.$row_perguntas[0].'[]" value="0"'.$value= ($checkychecky[0] == 1 ? "value=\"0\" " : "1")

but no success at all :(

Any ideas? Thanks




jQuery - remove value from input attribute

My jQuery script adds products IDs to an input type="hidden" value="id1,id2,id3"

Script is working and adds the ids on checkbox change, but if I uncheck the box, id must be remove from that input.

Part of my code:

<input type="hidden" value="100" class="productid100">

<script>

 var productid = jQuery(".productid<?php echo $_item->getId(); ?>").val();
 var defaultcombo = jQuery('.combodata').val();

 if(jQuery(this).is(":checked")) {

 jQuery('.combodata').attr("value", defaultcombo + productid+",");

 }else{

 var test = jQuery('#combo input:hidden[value=""]', productid+',').remove();
 console.log(test);

 }
</script>

<div id="combo">
<input type="hidden" class="hidden combodata" value="">
</div>

console.log()

Uncaught Error: Syntax error, unrecognized expression: 100,
at Function.ga.error (jquery-1.11.1.min.js:2)
at ga.tokenize (jquery-1.11.1.min.js:2)
at ga.select (jquery-1.11.1.min.js:2)
at Function.ga [as find] (jquery-1.11.1.min.js:2)
at m.fn.init.find (jquery-1.11.1.min.js:2)
at m.fn.init (jquery-1.11.1.min.js:2)
at new m (jquery-1.11.1.min.js:2)
at m.fn.init (jquery-1.11.1.min.js:2)
at m (jquery-1.11.1.min.js:2)
at HTMLInputElement.<anonymous> ...

This code is inside a PHP foreach for each product show in page.

At final I just need to add product id on checkbox click and remove the specify id on uncheck.

Problem is here:

jQuery('#combo input:hidden[value=""]', productid+',').remove();




Angular2 - reactive forms and multiple checkboxes not behaving correctly

I'm learning reactive forms still, and I want to have multiple checkboxes for a property that is array (e.g. hobby). So I defined the group as follows

this.myForm = this.fb.group({

    name: ['', Validators.required],

    hobbies: this.fb.array([])

});

Hobbies is an array: hobbies = ['Cooking', 'Swimming', 'Hiking', 'Dancing'];

Now, in HTML, I defined the checkboxes as follows:

<div>
  <span *ngFor="let hobby of hobbies">
    <label>
      <input type="checkbox" [value]="hobby" (click)="addToHobby(hobby)"> 
    </label>  
    <br />
  </span>
</div>

Now when checking an element it doesn't add it to the hobbies property at all, it just duplicates the actual HTML element. What am I doing wrong?

Here's the code: http://ift.tt/2mIOBZG




Input elements returning value as undefined while submitting the form

I am trying to submit the auto selected or user selected value. While submitting the form, input elements are returning value as undefined.

I have tried binding the values in multiple ways as suggested on different sites but nothing helped.

HTML code

<div ng-switch-when="textinput" class="form-group">
              <label class="control-label col-xs-3" for="textInput"><b>:</b></label>
              <div class="col-xs-9">
                <input type="text" class="form-control" id="textInput" pattern="tag.validation" ng-required="tag.required" ng-readonly="!tag.editable" ng-model="inputText" ng-init="inputText=tag.autofill" />
              </div>
            </div

JS code

$scope.submitForm = function() {
    $scope.formMain = true;
    $scope.footerMessage = false;
    $scope.getError="";
    $scope.error="";
    alert($scope.textBox);
  };

Please help on this. Link to Plunkr

Thank you in advance.




WPF - Ticking checkbox when clicking anywhere on a datagrid row.

Datagrid example

The picture shows an example of some items added in my datagrid. Right now I can only change each rows checkbox by clicking on it but I would like to be able to click anywhere on each row to change that rows checkbox. The row is styled in a controltemplate with two labels and a checkbox.

Any tips on how to achieve this?




How could I, from a table made of checkboxes, find informations about the position about the selected ones?

Some contest:

I have three tables in my database in MySQL, names are in italian.

  • "Attivita" (activity)
  • "Ambito" (scope)
  • An associative table of the two called "Azione" (action)

"Attività" and "Ambito" have each ones just two columns: ID and NOME. "Azione" has three foreign keys. One on the ID column of "Ambito", one of the ID column of "Attività" and one to a ID column of another table, that would auto-increment by 1 each time the "Submit" button is pushed and cointains other kind of informations. What I want to do, is to make a form where the user could populate che table "Azione" by selecting as many combination of "Attività" and "Ambito" as he like.

What I have done:

I made a dynamic table full of checkpoints with the rows coming from the table "Ambito" and the columns coming from "Attività" that looks like this:

 _ | 1 | 2 | 3 | 4 | 5 |
 a |   |   |   |   |   |
 b |   |   |   |   |   |
 c |   |   |   |   |   |
 d |   |   |   |   |   |

Where the user could select many checkboxes in it, like this:

 _ | 1 | 2 | 3 | 4 | 5 |
 a |   |   |   |   |   |
 b |   | x |   | x |   |
 c |   | x |   |   |   |
 d |   | x |   |   |   |

This is the code for this form for both the tamplate page and the code page in Smarty:

Template:

     <form name="{$formName}" id="inserisciazioni" method="{$formMethod}" action="{$formAction}" class="form_standard">
            <table>
                <tr>
                    <td></td>
                    {section name=attivita loop=$fAttivitaList}
                        <td>{$fAttivitaList[attivita].descrizione}</td>
                    {/section}
                </tr>
                {section name=ambito loop=$fAmbitoList}
                    <tr> 
                        <td>{$fAmbitoList[ambito].descrizione}</td>
                        {section name=attivita loop=$fAttivitaList}
                            <td><input type="checkbox" name="cbamb" class="cbAzione" id="{$servizi[key].nome}" value="{$servizi[key].nome}" /> </td>
                        {/section}

                    </tr>
                {/section}
            </table>
            <input name="{$btnSubmitName}" id="submitBtnInter" type="submit" class="default_submit" value="Invia" />
        </form>

"Logic code" page:

$listATT = new AttivitaList($db);
$listaAttivita = array();
for ($listATT->start(); !$listATT->isAfter(); $listATT->forth()) {
$rt = array('id' => $listATT->item()->getId(), 'descrizione' => $listATT->item()->getNome());
$listaAttivita[] = $rt;
}
$smarty->assign("fAttivitaList", $listaAttivita);

$listAMB = new AmbitoList($db);
$listaAmbito = array();
for ($listAMB->start(); !$listAMB->isAfter(); $listAMB->forth()) {
$rt = array('id' => $listAMB->item()->getId(), 'descrizione' => $listAMB->item()->getNome());
    $listaAmbito[] = $rt;
}
$smarty->assign("fAmbitoList", $listaAmbito);

What I want to do:

I want to find a way to know which checkboxes of the table are selected and which not, by finding informations about their position for both the row "Ambito" and the column "Attivita".

So, I could then add as many rows in "Azione" as many checkboxes are selected.




reactjs - make checkbox and row in table behave diffrently in material-ui

I want to make checkbox and row in table work differently. Now, when I click the row, checkbox is also clicked, and the other way work same, too. What I want to do is when I click the row, the dialog pops up, and when I click the checkbox, only checkbox is clicked, not dialog being worked.




dimanche 26 mars 2017

Errors when using 'ControllerAs' but works fine when using '$scope' in ng-repeat checkbox

When using '$scope' syntax, checking on individual checkbox correctly outputs its corresponding object name but when applying 'ControllerAs' syntax to same code, checking on individual checkbox abnormally generates error

$scope.users = [{.....}] //using $scope syntax
$scope.selected = [];

$scope.exist = function(item) {
  return $scope.selected.indexOf(item) > -1;
}
$scope.toggleSelection = function(item) {
  var idx = $scope.selected.indexOf(item);
  if (idx > -1) {
    $scope.selected.splice(idx, 1);
  } else {
    $scope.selected.push(item);
  }
}

Representation of above code using in ControllerAs

vm.users = [{....}] //Using 'Controller As' Syntax
vm.selected = [];

vm.exist = function(item) {
  return vm.selected.indexOf(item) > -1;
}
vm.toggleSelection = function(item) {
  var idx = vm.selected.indexOf(item);
  if (idx > -1) {
    vm.selected.splice(idx, 1);
  } else {
    vm.selected.push(item);
  }
}

Error returned in chrome developer tools

TypeError: vm.selected.indexOf is not a function at GridController.vm.exist (gridController.js:37)

Demo Controller As, http://ift.tt/2o7AtWY

Demo $Scope, http://ift.tt/2nYfQQg

Please what could be the issue or could this be a bug when Controller As syntax is applied in this context, thanks




jquery unable to remove attribute checked to a checkbox

I have a form generated with the answer of an ajax call to php page communicating with my database.

When I click on the submit button I gather through Jquery the content of the different inputs of the form (text,checkbox,textarea,...) in simple arrays to send them back to the database.

Now I want to reset the form after the submission. I failed to use myForm.reset() to clear everything (it did nothing) even with all the methods I found on stackoverflow and the Internet in general. So I decided to code the clear process myself.

To the main problem : I gather the value of the checked checkboxes with :

    var complement0=[];
    complement0.push($("input[name=foo]:checked").map(function() {
        return this.value;
    }).get());

And then try to uncheck the checkboxes. Here are the ways I tried to do it without success :

    $("input[name=foo]:checked").each(function() {
        $(this).removeAttr('checked');
    });

    $("input[name=foo]:checked").map(function() {
        return this;
    }).removeAttr('checked');

    $("input[name=prsFmtLng]:checked").attr('checked',false);

    $("input[name=prsFmtLng]:checked").removeAttr('checked');

Since it looks like it is simple when other people talk about this, either I don't understand what I am doing or I am just missing something. Any help is welcomed.




ItemView may not be null

I'm trying to retrieve all the checkboxes from my RecyclerView in order to uncheck them. However, this error is shown. Below are the classes that LogCat points to.

java.lang.IllegalArgumentException: itemView may not be null
             at android.support.v7.widget.RecyclerView$ViewHolder.<init>(RecyclerView.java:10314)
             at br.com.ufrn.marceloaugusto.tasklist.adapter.ProdutoAdapter$ProdutosViewHolder.<init>(ProdutoAdapter.java:0)
             at br.com.ufrn.marceloaugusto.tasklist.MainActivity.onOptionsItemSelected(MainActivity.java:93)

MainActivity.java

public class MainActivity extends BaseActivity {

    //private SQLiteDatabase banco;

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

        if (savedInstanceState == null) {
            FragmentProdutos frag = new FragmentProdutos();
            getSupportFragmentManager().beginTransaction().add(R.id.container, frag).commit();
        }

        //FAB
        findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                snack(view, "Adicionar produto");
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_desmarkAll) {
            RecyclerView recycler = (RecyclerView) findViewById(R.id.recyclerView);
            ProdutoAdapter.ProdutosViewHolder holder = null;
            int id = 0;
            for (int i = 0; i < recycler.getAdapter().getItemCount(); i++) {
                holder = new ProdutoAdapter.ProdutosViewHolder(recycler.getChildAt(i)); **//Line 93**
                if (holder.checkBox.isChecked()) {
                    holder.checkBox.setChecked(false);
                }
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }} 

ProdutoAdapter.java

public class ProdutoAdapter extends RecyclerView.Adapter<ProdutoAdapter.ProdutosViewHolder> {
private final Context context;
private final List<Produto> produtos;
//Interface para expor os eventos de toque na lista
private ProdutoOnClickListener produtoOnClickListener;
private ProdutoOnCheckListener produtoOnCheckListener;

public ProdutoAdapter(Context context, List<Produto> produtos, ProdutoOnClickListener produtoOnClickListener, ProdutoOnCheckListener produtoOnCheckListener) {
    this.context = context;
    this.produtos = produtos;
    this.produtoOnClickListener = produtoOnClickListener;
    this.produtoOnCheckListener = produtoOnCheckListener;
}

@Override
public int getItemCount() {
    return this.produtos != null ? this.produtos.size() : 0;
}

@Override
public ProdutosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.adapter_produto, parent, false);
    ProdutosViewHolder holder = new ProdutosViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(final ProdutosViewHolder holder, final int position) {
    Produto p = produtos.get(position);
    holder.tNome.setText(p.getNome());
    //holder.tPreco.setText(String.valueOf(p.getPreco()));
    if (produtoOnClickListener != null) {
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                produtoOnClickListener.onClickProduto(view, position);
            }
        });
    }
    if (produtoOnCheckListener != null) {
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                produtoOnCheckListener.onCheckProduto(view, position);
            }
        });
    }
}

public interface ProdutoOnClickListener {
    public void onClickProduto(View view, int idx);
}

public interface ProdutoOnCheckListener {
    public void onCheckProduto(View view, int position);
}

public static class ProdutosViewHolder extends RecyclerView.ViewHolder {
    public TextView tNome;
    //public TextView tPreco;
    CardView cardView;
    public CheckBox checkBox;
    public ProdutosViewHolder(View view) {
        super(view);
        tNome = (TextView) view.findViewById(R.id.nomeProduto);
        //tPreco = (TextView) view.findViewById(R.id.precoProduto);
        cardView = (CardView) view.findViewById(R.id.card_view);
        checkBox = (CheckBox) view.findViewById(R.id.checkProduto);
    }
}

}




MySQL/PHP - Checkbox array to delete multiple rows from database

i'm having some trouble passing Form checkbox array as mysql_query in order to delete multiple rows from table.

The structure is as follows:

HTML

<form action="usunogrod.php" method="POST" enctype="multipart/form-data">
    <?php
     $ogrodysql = "SELECT id_ogrodu, nazwa FROM ogrody";
     $result = mysqli_query($con, $ogrodysql);

     if (mysqli_num_rows($result) > 0) {

         while($row = mysqli_fetch_assoc($result)) {
              echo "• " . $row["id_ogrodu"]. " " . $row["nazwa"]. "<input type='checkbox' name='removegarden[]' value=" .$row["id_ogrodu"]." <br><br>";
         }
     } 
     else {
         echo "0 results";
     }
     ?>

    <br><br>
    <input type="submit" value="Usuń zaznaczony ogród."/>
</form>

PHP for processing form in usunogrod.php

<?php

$db_host = 'xxxxx';
$db_user = 'xxxxx';
$db_pwd = 'xxxxx';
$con = mysqli_connect($db_host, $db_user, $db_pwd);  
$database = 'xxxxx';

if (!mysqli_connect($db_host, $db_user, $db_pwd))
    die("Brak połączenia z bazą danych.");

if (!mysqli_select_db($con, $database))
    die("Nie można wybrać bazy danych.");

function sql_safe($s)
{
    if (get_magic_quotes_gpc())
        $s = stripslashes($s);
    global $con;
    return mysqli_real_escape_string($con, $s);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {   

    $ogrod_id = trim(sql_safe($_POST['removegarden[]']));

    if (isset($_POST['removegarden[]'])) {

                mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu='$ogrod_id'");

                $msg = 'Ogród został usunięty.';
    }
    elseif (isset($_GET['removegarden[]']))
        $msg = 'Nie udało się usunąć ogrodu.';
};
?>

MySQL table

ogrody

#      id_ogrodu      nazwa
       1              garden1

How may i process an array from checkboxes form so that i will be able to pass a query to delete all checked elements?

EDIT:

I have been able to make it work to a moment where it only deleted one of the checked positions, or the other time just got an error saying i can't pass and array to mysqli_query.




tkk checkbutton appears when loaded up with black box in it

I create a check button / box, with the following call

x=ttk.Checkbutton(tab1,state='disabled',command = lambda j=i,x=k: fCheckButton(j,x)) x.state(['selected'])

The box appears fine and is selected, but it appears on load up, with a black box in it, which seems to have nothing to do with the state of it.

I have looked for reasons why, but can't actually find anyone with the same problem.

thanks




Apply class on checkboxes collection

I would like to add a class on each instance of my collection. This is my checkboxes collection :

.cov-pick-row.w-row
      = f.input_field :inspiration_image_ids, 
        :collection => @inspiration_images.map {|img| [image_tag(img.image.url(:thumb)).html_safe, img.id] },
        class: 'image-cov-pick', 
       :include_blank => '(All)', 
       :multiple => true, 
       :selected => [''], as: :check_boxes

I would like an input like this :

            .cov-pick-row w-row
              .w-col.w-col-2 w-col-small-4.w-col-tiny-6
                .image-cov-pick
                  = image_tag('my_image1.jpg')
              .w-col.w-col-2 w-col-small-4.w-col-tiny-6
                .image-cov-pick
                  = image_tag('my_image2.jpg')
              ...

So my questions is : How to add this class .w-col.w-col-2 w-col-small-4.w-col-tiny-6 above the class image-cov-pick for each instances ?

Thank you for your help




checkbox property check value not updating in knockout js

I am working on Knockout Js. I have a page where I have three checkbox and its under foreach loop. Here is code

 <div class="form-horizontal" id="ko-bind-element">
            <input type="hidden" id="serverJSON" value="@Newtonsoft.Json.JsonConvert.SerializeObject(Model)" />
            <div data-bind="foreach: procedures">
                <div data-bind="template: { name: Mode(), data: $data }"></div>
            </div>
        </div>

<script type="text/html" id="procedure">
            <table class="table table-bordered" >
                <tr>

                    <td class="col-md-3"><span data-bind="text: Name"></span></td>
                    <td><input type="checkbox" data-bind="attr: { name: (VId.length > 0) ? VId : Name },checked: AlreadyCompleted" /></td>
                    <td><input type="checkbox" data-bind="attr: { name: (VId.length > 0) ? VId : Name },checked: NotApplicable" /></td>
                    <td><input type="checkbox" data-bind="attr: { name: (VId.length > 0) ? VId : Name },checked: CreateNew" /></td>

                </tr>
                <tr>
                    <td colspan="4" style="padding:0;">

                        <div data-bind="if: CreateNew">
                            <textarea style="margin-top:10px; margin-bottom:10px;" class="col-md-offset-3 col-md-8" data-bind=" value : Text"></textarea>
                            <div class="clearfix"></div>
                        </div>
                    </td>
                </tr>
            </table>

        </script>

As there are three checkbox per row and I wanted only one of them should be selected so I have this jquery function which selects one checkbox at time per row

$("input:checkbox").on('click', function () {

        debugger;

        // in the handler, 'this' refers to the box clicked on
        var $box = $(this);
        if ($box.is(":checked")) {
            // the name of the box is retrieved using the .attr() method
            // as it is assumed and expected to be immutable
            var group = "input:checkbox[name='" + $box.attr("name") + "']";
            // the checked state of the group/box on the other hand will change
            // and the current value is retrieved using .prop() method
            $(group).prop("checked", false);
            $box.prop("checked", true);
        } else {
            $box.prop("checked", false);
        }
    });

But problem is now, When I check 1st checkbox then uncheck it. Then Check second checkbox and submit data. Both 1st and 2nd show checked . So don't know whether its Knockout issue.

Here is binding code

viewModel = {
        MtocFormID: 0,
        procedures: ko.observableArray(),
        dateid:null
    };


    $(document).ready(function () {
        var data = JSON.parse($("#serverJSON").val());
        viewModel.MtocFormID = ko.observable(data.ID);
      // viewModel.dateid = ko.observable(data.ExpiryDate)

        $(data.TemplateProcedure).each(function (index, element) {
            var mappedItem = {
            //    otherSafetyPro: ko.observableArray([]),
                VId: ko.observable(element.VId),
                TemplateID: ko.observable(element.TemplateID),
                ProcedureTemplateID: ko.observable(element.ProcedureTemplateID),
                Name: ko.observable(element.Name),

                AlreadyCompleted: ko.observable(element.AlreadyCompleted),
                NotApplicable: ko.observable(element.NotApplicable),
                CreateNew: ko.observable(element.CreateNew),
                Text: ko.observable(element.Text),
                Mode: ko.observable("procedure")
            }
            viewModel.procedures.push(mappedItem);
        });

        ko.cleanNode(document.getElementById("ko-bind-element"));
        ko.applyBindings(viewModel, document.getElementById("ko-bind-element"));
        form08wizard.submitData(getSubmitData);
    });




Checkbox item which has been checked needs to get added to php mysql database

I have many checkbox items where each employee has access to different department . I want to add checked items into database.

code to display access to doors if checked

 $door1 = $_POST['door1'];
 echo ' dooraccess is available for ' .$door1. '<br>'; 

 $door2 = $_POST['door2'];
 echo 'dooraccess is available for  ' .$door2. '<br>'; 

 $door3 = $_POST['door3'];
 echo 'dooraccess is available for  ' .$door3. '<br>'; 

 $door4 = $_POST['door4'];
 echo 'dooraccess is available for  ' .$door4. '<br>'; 

 $door5 = $_POST['door5'];
 echo 'dooraccess is available for  ' .$door5. '<br>'; 

 $door6 = $_POST['door6'];
 echo 'dooraccess is available for  ' .$door6. '<br>'; 

 $door7 = $_POST['door7'];
 echo 'dooraccess is available for  ' .$door7. '<br>'; 

 $door8 = $_POST['door8'];
 echo 'dooraccess is available for  ' .$door8. '<br>'; 

 $door9 = $_POST['door9'];
 echo 'dooraccess is available for  ' .$door9. '<br>'; 

 $door10 = $_POST['door10'];
 echo 'dooraccess is available for  ' .$door10. '<br>'; 

 $door11 = $_POST['door11'];
 echo 'dooraccess is available for  ' .$door11. '<br>'; 

 $door12 = $_POST['door12'];
 echo 'dooraccess is available for  ' .$door12. '<br>'; 

In case the values that was not checked then it will display the error as below:

Undefined index: door7 in [since door7 was not checked]

Code to insert these values along with other values to database php mysql database

 if(isset($_POST['submit']))
  { 
   $query = "INSERT INTO form_details1(firstname,secondname,location,designation,fileno,doa,doj,cardtype1,cardcolor,cardtype2,door1,door2,door3,door4,door5,door6,door7,door8,door9,door10,door11,door12,door13) VALUES('$firstname','$secondname','$location','$designation','$fileno','$doa','$doj','$cardtype1',$cardcolor,'$cardtype2','$door1','$door2','$door3','$door4','$door5','$door6','$door7','$door8','$door9','$door10','$door11','$door12')"; //query
  if(mysqli_query($connect,$query)){ //check query executed or not
     echo 'inserted' . '<br>' ;
   }

Query doesn't insert into database since query has the values which is unchecked

I want to check all the checked items using if loop or any other means and enter only those items that has been checked. How can I do this ?




samedi 25 mars 2017

Android: Custom ArrayAdapter for SmoothCheckBox

I'm trying to get a grid of SmoothCheckboxes (can be found here http://ift.tt/2nnWIcT), and the grid populates with everything I throw at it successfully, besides the SmoothCheckBox itself. What am I doing wrong here?

My Custom Adapter:

    public class ExercisesAdapter extends BaseAdapter {

private Context context;
private final SmoothCheckBox[] checkboxes;

public ExercisesAdapter(Context context, SmoothCheckBox[] checkboxes) {
    this.context = context;
    this.checkboxes = checkboxes;
}

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

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View gridView;

        gridView = new View(context);
        // get layout from mobile.xml
        gridView = inflater.inflate(R.layout.exercise, null);
        TextView number = (TextView) gridView.findViewById(R.id.tv_exerciseName);
        number.setText("No. " + position);
        SmoothCheckBox checkBox = checkboxes[position];

        return gridView;

}}

My layout for the checkboxes:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:app="http://ift.tt/GEGVYd"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tv_exerciseName"
        android:layout_width="31dp"
        android:layout_height="22dp"
        android:textAlignment="center"
        tools:layout_editor_absoluteX="1dp"
        tools:layout_editor_absoluteY="2dp" />

    <cn.refactor.library.SmoothCheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="14dp"
        android:checked="false"
        app:layout_constraintTop_toBottomOf="@+id/tv_exerciseName"
        tools:layout_editor_absoluteX="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp" />
</android.support.constraint.ConstraintLayout>




Change checkbox state

I am trying to create a ListView with multiple rows. Each row have a checkbox + text. This is my implementation of a ListView:

class ListExample extends Component {

  constructor() {
      super();
      const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      this.state = {
        dataSource: ds.cloneWithRows(["hey1", "hey2", "hey3", "hey4"]),
      };
    }

    render() {
      return (
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(data) => <Row data={data} />}
        />
      );
    }
}
export default ListExample;

This is my implementation of a row:

import React from 'react';
import { CheckBox } from 'native-base';
import { View, Text, StyleSheet} from 'react-native';

const Row = (props) => (
  <View style={styles.container}>
    <CheckBox onPress={props.onPress} checked={false} />
    <Text style={styles.text}>
      { props.data }
    </Text>
  </View>
);
export { Row };

Now I need create behavior on the checkbox. My goal is when a person click on the checkbox the box change the state to checked.

How can I do that ?




Stop checkboxes with display:none from submitting data

Good afternoon , basically I have a lot of checkboxes that when they are clicked they open other checkboxes and finally the last checkbox when clicked opens a small form with : email, phonenumber, name .

My issue is what happens when a user selects a checkbox , gets to the form , completes the data inside the form , then he changes his mind and unchecks all the checkboxes and opens other one checkboxes and complete the form in that ?

Right now what im doing is when a user clicks another checkbox, I change the other checkboxes to display none. But from my understanding at the end when I submit the information to the database the information that was already wrote , which receives display:none is sent aswell ...

How can I proceed this ? this are my paste bins. http://ift.tt/2n4OfbV -html5 code http://ift.tt/2mC7YDu -

Hope I explained myself well enough . Thanks




submit default value if the checkbox is unchecked

i have a html form submitting to my spring java controller. i have a small problem here.

 <table id="example1" class="table table-bordered table-striped">
                            <thead>

                            <tr>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Age</th>
                                <th>Sex</th>
                                <th>District</th>
                                <th>VDC/MUNICIPAL</th>
                                <th>Ward No.</th>
                                <th>Camp Visited?</th>
                                <th>Consent</th>
                                <th>Actions</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr th:each="persons : ${part}">
                                <form method="post" th:action="@{/addParticipant}" enctype="multipart/form-data">
                                    <input type="hidden" th:value="${persons.id}" name="id">
                                    <td>
                                        <span class="hidden" th:text="${persons.name}"></span>
                                        <input type="text" name="name" th:value="${persons.name}">
                                    </td>
                                    <td>
                                        <span class="hidden" th:text="${persons.lastName}"></span>
                                        <input name="lastName" type="text" th:value="${persons.lastName}">
                                    </td >
                                    <td>
                                        <span class="hidden" th:text="${persons.age}"></span>
                                        <input name="age" type="text" th:value="${persons.age}">
                                    </td>
                                    <td>
                                        <span class="hidden" th:text="${persons.sex}"></span>
                                        <input name="sex" type="text" th:value="${persons.sex}">
                                    </td>
                                    <td>
                                        <span class="hidden" th:text="${persons.district}"></span>
                                        <input name="district"  type="text" th:value="${persons.district}">
                                    </td>
                                    <td>
                                        <span class="hidden" th:text="${persons.vdcMun}"></span>
                                        <input name="vdcMun"  type="text" th:value="${persons.vdcMun}">
                                    </td>
                                    <td>
                                        <span class="hidden" th:text="${persons.wardNo}"></span>
                                        <input name="wardNo" type="text" th:value="${persons.wardNo}">
                                    </td>
                                    <td>
                                        <div class="checkbox">
                                            <input type='hidden' value='no' name='attendStatus' id="attendStatusHidden">
                                            <input type="checkbox" value="yes" name="attendStatus" id="attendStatus">
                                        </div>

                                    </td>
                                    <td>
                                        <div class="form-control">
                                            <input type="hidden" name="file" value="null">
                                            <input id="file" type="file" name="file" accept="image/*">
                                        </div>
                                    </td>
                                    <td>
                                        <button type="submit" class="btn btn-success" id="submitButton">Submit</button>
                                    </td>
                                </form>
                            </tr>
                            </tbody>
                        </table>

so what i am trying to do is whenever my checkbox is checked it should send the value yes else no.

i tried to put the two input fields with one being hidden. but whenever i submit the form it posts both yes and no on my table.

i tried javascript like this.

   window.onload = function(){
    if(document.getElementById("attendStatus").checked) {
        document.getElementById('attendStatusHidden').disabled = true;
    }
};

i am trying to disable hidden field whenever i check the checkbox but still it posts both yes,no on my table.

how can i solve this with javascript or HTML itself, if there's any?