dimanche 31 juillet 2016

How to check or uncheck checkboxes by cliking on text instead of checkbox itself?

I have seen it on several webpages (cannot recall where exactly atm) where I am able to check or uncheck checkboxes by clicking on the text in front of the checkbox. I know how to do it in JavaScript (create a span with onclick()) , but I want to know if there is any way I can do it without JavaScript.




How to Set ID's on programmatically created checkboxes?

Hello everyone and coding lovers,

at the moment i am working on a small app that helps me to track my nutrition.

Now, i build a Layout with an Adapter.

For this purpose im using a SimpleCursorAdapter because all needed data comes from my database.

Everything went fine except one thing:

All checkboxes has the same id. So im not able to check each of them. There is one solution i know how it can be solved but in this case i cant use an xml file to generate ids because i dont know how many checkboxes will be next time i run the app.

Here is my code:

public void getIdAndDate()
{
    db = new DATABASE(this);

    SQLiteDatabase sqldb = db.getReadableDatabase();

    String[] Columns = {"_id", "date"};
    int[] toViews = {R.id.entry_id, R.id.entry_date};

    Cursor cursor1;

    cursor1 = sqldb.query(db.TABLE_DAILY_CONSUMPTION, Columns, null, null, null, null, null);

    numRows = cursor1.getCount();

    int id[] = new int[numRows];
    String date[] = new String[numRows];

    for(int i = 0; i<numRows; i++)
    {
        cursor1.moveToNext();
        id[i] = cursor1.getInt(0);
        date[i] = cursor1.getString(1);
    }

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.layout_entry, cursor1, Columns, toViews, 0);
    entries.setAdapter(adapter);
}

And this is my Layout:

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

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/entry_id"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:textSize="20sp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/entry_date"
    android:layout_gravity="center_horizontal"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:textSize="20sp"/>

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/entry_selection"
    android:layout_gravity="right"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    />

I really try to figure out how i can solve the problem but i cant even imagine which possibilities i have.

I'm still looking for a solution.




Add/remove some text to div after radiobox is checked/unchecked

I have several radio and checkboxes for displaying some divs. I need to display separate div which show text(e.g. name of author) after clicking on radiobox and also add some text to previous text after clicking on checkboxes. Is it possible to create something like this with the help of css/javascript ? Any advice ? I think that I need to add/remove classes with "content:"bla bla"" in css.




samedi 30 juillet 2016

how to send true/false value through checkbox in razor

Here is my Razor View :-

@model _24By7CallAndBPOPvtLtd.Models.Job_Det
           ............
 <div class="form-group">
                @Html.LabelFor(model => model.Picture_id, "Picture Required?", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                   @Html.CheckBox("Picture_Required", model => model.Picture_id.Picture_Required)
                </div>
            </div>
<div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" /></div></div>

Here is my table:-

public partial class Picture
    {
public Picture()
    {
        this.Job_Applied = new HashSet<Job_Applied>();
        this.Job_Det = new HashSet<Job_Det>();
    }

    public int Picture_Id { get; set; }
    public string Pic_Path { get; set; }
    public Nullable<bool> Picture_Required { get; set; }

    public virtual ICollection<Job_Applied> Job_Applied { get; set; }
    public virtual ICollection<Job_Det> Job_Det { get; set; }
}

i need to send true/false value to picture table by check/uncheck the checkbox.. please help me




checkbox not selected in a shiny app

I need to prepare a shiny app for a school project. This is a link of what it is supposed to look like

http://ift.tt/2am3byr

If you look at the app you see there is a checkbox named medals.When you open the app they are all selected but in the event the user decides to uncheck them all there should be a small error and no graph should be drawn.

I am having trouble getting to this, when I uncheck all the boxes in my app it draws an empty drawing

This is the important part of the code:

 fluidRow(
  column(3,checkboxGroupInput("Medals", label = strong("Medals"),
  choices = list("Total" = "TOTAL", "Gold" = 'GOLD',
  "Silver" = 'SILVER','Bronze'='BRONZE'),
   selected = c('TOTAL','GOLD','SILVER','BRONZE')))),

  fluidRow(
    mainPanel(plotOutput('coolplot'),width = '40%'))
)    
)
  server <- function(input, output){output$coolplot<-renderPlot(plot.medals2(input$country,
  input$Startingyear,input$Endingyear,input$Medals))}
  shinyApp(ui = ui, server = server)

I am using a function plot.medals2 that gets a vector of medals ,start year, ending year, country and returns a drawing of the graph.




VBA CheckBox Not Checked If Statement Won't Initiate

this super simple thing is currently driving me crazy. I have an If statement to handle the CheckBox_Click() event which is supposed to do one of two things depending on the status of the CheckBox. While it works just fine when the box becomes checked, it just won't do anything when the box is unchecked. I know the code is firing simply by putting a MsgBox to tell me, but the If statement won't initiate. See code below:

Sub Chase_Visa_Click()
    'Check new button status for action.
    If Sheets("<Sheet Name>").Shapes("<CheckBox Name>").OLEFormat.Object.Value = 1 Then
        MsgBox ("Box checked.")
    ElseIf Sheets("<Sheet Name>").Shapes("CheckBox Name>").OLEFormat.Object.Value = 0 Then
        MsgBox ("Box unchecked.")
    End If
End Sub

From what I've read, the value for unchecked is 0. I've also tried things like ".Checked = False". Thank you very much for your help.




Linking Checkbox Values from MS Access Database in C#

I have a winForm application that connects to a MS Access database. When i load the table in a datgridview i want to be able to populate a checkbox value that's in my WinForm application based on whether the same checkbox is selected or not selected in my database. In other words after my table is loaded when i click on a record the value of the check box will changed based on whether it is checked or unchecked in the database. I am doing the same thing with textboxes & combo boxes but i am unsure how to do it with the checkboxes. Here is my code:

private void dataGridViewWendys_CellContentClick(object sender, DataGridViewCellEventArgs e)//Start of code for Wendys DataGridView Cell Content
{
    if(e.RowIndex>=0)
    {
        DataGridViewRow row = dataGridViewWendys.Rows[e.RowIndex];
        txt_ID.Text = row.Cells["ID"].Value.ToString();
        txt_Nickname.Text = row.Cells["Nickname"].Value.ToString();
        txt_ProjNumber.Text = row.Cells["ProjectNumber"].Value.ToString();
        txt_ProjYear.Text = row.Cells["ProjectYear"].Value.ToString();
        txt_StoreNumber.Text = row.Cells["StoreNumber"].Value.ToString();
        txt_StreetAddress.Text = row.Cells["StreetAddress"].Value.ToString();
        txt_city.Text = row.Cells["City"].Value.ToString();
        cb_State.Text = row.Cells["State"].Value.ToString();
        txt_ZipCode.Text = row.Cells["Zipcode"].Value.ToString();
        cb_AssetType.Text = row.Cells["AssetType"].Value.ToString();
        cb_BaseModel.Text = row.Cells["BaseModel"].Value.ToString();
        cb_BldgPrototypeYear.Text = row.Cells["BldgPrototypeYear"].Value.ToString();
        cb_UpgradeClass.Text = row.Cells["UpgradeClass"].Value.ToString();
        cb_ExtWallStructure.Text = row.Cells["ExtWallStructure"].Value.ToString();
        cb_NewWallStructure.Text = row.Cells["NewWallStructure"].Value.ToString();
        ckb_StructDwgs.Checked = row.Cells["StructuralDwgs"].Value;
        cb_BladeDesign.Text = row.Cells["BladeDesign"].Value.ToString();
        //ckb_CurtainWall.Checked = row.Cells["CurtainWall"].Value.ToString();
        //Corragated Metal Above Windows.c = row.Cells["CorrugatedMlFrt"].Value.ToString();
        cb_Addition.Text = row.Cells["Addition"].Value.ToString();
        //ckb_SecondPUW.Checked = row.Cells["SecondPUW"].Value.ToString();
        //ckb_PUWExtention.checked = row.Cells["PUWWindowExtention"].Value.ToString();
        cb_ExtFndType.Text = row.Cells["ExstFoundationType"].Value.ToString();
        cb_NewFndType.Text = row.Cells["NewFoundationType"].Value.ToString();
        //ckb_PUWVestibule.Checked = row.Cells["PUWVestibule"].Value.ToString();
        //ckb_NonPUWVestibule.Checked = row.Cells["NonPUWVestibule"].Value.ToString();
        cb_DriveThruType.Text = row.Cells["DriveThruType"].Value.ToString();
        cb_TrashEnclosure.Text = row.Cells["TrashEnclosure"].Value.ToString();
        cb_MenuboardType.Text = row.Cells["DigitalStatic"].Value.ToString();
        cb_Patio.Text = row.Cells["Patio"].Value.ToString();
        //ckb_ExtTrayWash.Checked = row.Cells["ExtgTrayWash"].Value.ToString();
        cb_SelfServe.Text = row.Cells["SelfServe"].Value.ToString();
        //ckb_SpandrelGlass.Checked = row.Cells["SpandrelGlass"].Value.ToString();
        cb_CounterStyle.Text = row.Cells["CounterStyle"].Value.ToString();
        cb_RaisedCeiling.Text = row.Cells["RaisedCeiling"].Value.ToString();
        //ckb_KitchenWork.Checked = row.Cells["KitchenWork"].Value.ToString();
        //ckb_ElecGasHeat.Checked = row.Cells["ElecGasHeat"].Value.ToString();
        //ckb_ElecGasfryer.Checked = row.Cells["ElecGasFryers"].Value.ToString();
        //ckb_ElecGasGrille.Checked = row.Cells["ElecGasGrilles"].Value.ToString();
        //ckbBlockBands.Checked = row.Cells["BlockBands"].Value.ToString();
        list_Notes.Text = row.Cells["Notes"].Value.ToString();
        cb_ExtRoofStructure.Text = row.Cells["ExtRoofStructure"].Value.ToString();
        cb_NewRoofStructure.Text = row.Cells["NewRoofStructure"].Value.ToString();




unchecked checkbox when creating a shiny app in R

I need to create a shiny app for a school project this is a link of how it is supposed to look like:

http://ift.tt/2am3byr

Now if you look there is a checkbox named medals and the user needs to select which medals he wants to be plotted. When the user does not select anything (when you first enter the app they are all selected so he needs to uncheck) there needs to be a small red error message saying year 'not found. I don't know how to turn the shiny app to a website so I can't attach what I get but basically instead of getting an error message I get an empty plot. This is the code

library(shiny)
library(ggplot2)
library(dplyr)
library(reshape)
source('helpers.R')

ui<-shinyUI(fluidPage(
  titlePanel("The R Olympic Medal Viewer"),

  fluidRow(column(3,
  selectInput("country", label = strong("Country"), 
  choices = list("Australia"='AUS', "China" = 'CHN',
  " Spain" = 'ESP','France'='FRA','United Kingdom'='GBR','Germany'='GER',
  'South korea'='KOR','Netherlands'='NED','Russia'='RUS','United states'='USA'), selected = 1))),

  fluidRow(column(3, 
  sliderInput("Startingyear", label = strong("Starting year"),
  min = 1896, max = 2008,value = 1896 )
  )),

  fluidRow(column(3, 
  sliderInput("Endingyear", label = strong("Ending year"),
   min = 1896, max = 2008,value = 2008 )
  )
  ),

  fluidRow(
  column(3,checkboxGroupInput("Medals", label = strong("Medals"),
  choices = list("Total" = "TOTAL", "Gold" = 'GOLD',
  "Silver" = 'SILVER','Bronze'='BRONZE'),
   selected = c('TOTAL','GOLD','SILVER','BRONZE')))),

  fluidRow(
    mainPanel(plotOutput('coolplot'),width = '40%'))
)    
)
  server <- function(input, output){output$coolplot<-renderPlot(plot.medals2(input$country,
  input$Startingyear,input$Endingyear,input$Medals))}
  shinyApp(ui = ui, server = server)

What can I do to get it to be similar to what is on the website?




check box text not appearing in android studio

Check box text not appearing in my layout file in android studio. This is the xml code.layout image. the text "checkbox" only appearing. have used styles for check boxes and placed the check boxes inside the scroll view.

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:fillViewport="false"
    android:orientation="vertical"
    android:padding="5dp">


    <LinearLayout style="@style/QuestionSetStyle">

        <TextView
            style="@style/QuestionStyle"
            android:text="@string/text_Q1" />

        <LinearLayout style="@style/AnswerSetStyle">

            <CheckBox
                android:id="@+id/cb_1_a"
                style="@style/CheckBox"
                android:textColor="#ffff00"
                android:text="@string/text_FRANCE" />

            <CheckBox
                android:id="@+id/cb_1_b"
                style="@style/CheckBox"
                android:text="@string/text_BEIJING" />

        </LinearLayout>

        <LinearLayout style="@style/AnswerSetStyle">


            <CheckBox
                android:id="@+id/cb_1_c"
                style="@style/CheckBox"
                android:text="@string/text_NEWDELHI" />


            <CheckBox
                android:id="@+id/cb_1_d"
                style="@style/CheckBox"
                android:text="@string/text_SEOUL" />

        </LinearLayout>
    </LinearLayout>


</ScrollView>




How to save a refernece to a checkbox in a table row?

After a checkbox has been checked I display a form. If the form is canceled, I wish to uncheck the box.

In the HTML, I define:

<input id="current-checkbox" type="checkbox" class="hidden" />

In the associated JS I save the current position:

var curRow = $(this).closest('.trow').find('input[type=checkbox]');
$("#current-row",curRow);

console.log shows:

$("#current-checkbox")
[<input id=​"current-checkbox" type=​"checkbox" class=​"hidden">​]

The cancel form JS:

$("#cancel-email").on('click', function (e) {
    debugger
    e.preventDefault();
    setTimeout(function () { showMessage(1, 'Emails not sent.') }, 2000);
    setTimeout(function () { hideEmailElems(); }, 2000);
    $("#current-checkbox").find("input[type=checkbox]").prop("checked", false).focus();
});

console.log:

$("#current-checkbox").find("input[type=checkbox]").length
0

What is the correct jQuery selector to locate saved the checkbox?




how to get focus when checked chekbox?

I have set setFocusable(false) in my edit text. But when i checked checkbox i want to get focus in my edittext. below is example.

cbIsGap.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) {

            edittext1.setFocusable(true);
            edittext1.setClickable(true);

        }else {


            edittext1.setFocusable(true);
            edittext1.setClickable(true);

        }
    }
});

I am trying above example but i am not getting focus when i checked checkbox




How to sort tables based on checked row?

I have a questions regarding how to sort the table by checkbox column. Meaning that if the user check the checkbox, it will automatically put the checked one on top of the table (first row and so on). Seriously i never do this sorting based on checkbox column before. Also i search for it but all i saw was sorting the table when clicking the table header. I don't want that. I want to it to be dynamically update the table whenever user check it and bring the checked row to the top. I have this pic hereenter image description here

So i am using tablesorter and for search is ajax livesearch. Thus, if only i can make the checked row to be on first row, it would make it easier for the user to identify its checked row right.

Here is my code for ajax(index.php)

function ajaxSearchUpdater(p){
        $("#result").show();

        var x = $("#search").val();
        var y = $("#edulevel").val();
        var pagelim = $("#pagefpe").val();
        var pagenumber = p;
        var checkb = $(".sBorrow").val()
        $.ajax({
            type:'POST',
            url:'userres.php',
            data:'q='+x+'&e='+y+'&pagelim='+pagelim+'&pageno='+pagenumber+'&checkb='+checkb,
            cache:false,
            success:function(data){
                $("#result").html(data)
            }
        });
    }


    function setsession(sessionid,action){
        $("#totalselection").show();
        $.ajax({
            type:'POST',
            url:'test.php',
            data:'sBorrow='+sessionid+'&action='+action,
            cache:false,
            success:function(data){
                var out = "<p align='center' style='text-decoration:none;color:white;'>Total Selection: "+data+"<br/>Click here to submit your request<a href='borrowform.php' style='text-align:center;'><input type='button' value='REQUEST'></a>&nbsp;&nbsp;&nbsp;||&nbsp;&nbsp;&nbsp;Click here to clear the selection <a href='#' style='text-align:center;'><input type='button' value='CLEAR'></a></p>";
                $("#totalselection").html(out)
            }
        });
    }



    $(document).ready(function(e) {
        ajaxSearchUpdater(1);           // fires on document.ready
        $("#search").keyup(function() {
            ajaxSearchUpdater(1);           // your function call
        });
        $("#edulevel").click(function() {
            ajaxSearchUpdater(1);           // your function call
        });
        $("#pagefpe").click(function() {
            ajaxSearchUpdater(1);           // your function call
        });
        $(document).delegate('.sBorrow', 'change', function(){
            var sBorrowClass = $(this).attr('class');
            var sBorrowValue = $(this).attr('value');
            var sBorrowName = $(this).attr('name');

            if(this.checked){
                setsession(sBorrowValue, "SET");
            }
            else{
                setsession(sBorrowValue, "UNSET");
            }

            //$("#name_" + cont_det_id).hide(); //hide span
            //$("#input_name_" + cont_det_id).show(); //show editable box

        })/*.delegate('.sBorrow', 'keypress', function (e) {
            if(e.which == 13) { //if statement for pressing enter button
                var cont_det_id = $(this).attr('id');
                //alert cont_det_id good here
            }
        });*/

Here is my code for echoing the table from database (userres.php)

if($stmt->rowCount() > 0){
    $r=$stmt->fetchAll();
    echo "<table class='tablesorter-blackice' id='myTable' style='width:97%; table-border: 1'>";
        echo "<thead>";
        echo "<tr>";
        echo "<th>No.</th>";
        echo "<th>No.Matric</th>";
        echo "<th>Name</th>";
        echo "<th>Programme</th>";
        echo "<th>Title</th>";
        echo "<th>Thesis Level</th>";
        echo "<th>Serial Number</th>";
        echo "<th>Availability</th>";
        echo "<th>Select book (Max 3)</th>";
        echo "</tr>";
        echo "</thead>";
        echo "<tbody>";

        if(isset($_SESSION['sBorrow']))
            $arraynosiri = $_SESSION['sBorrow'];
        else
            $arraynosiri = array();



    foreach($r as $row){

            echo "<tr align='center'><td>". ($startrow+1) ."</td><td>". $row['matricno'] ."</td><td>". $row['studentname'] ."</td><td>". $row['programme'] ."</td><td>". $row['title'] ."</td><td>". $row['thesis_level'] ."</td><td>". $row['serialno'] ."</td><td>". $row['bavailable'] ."</td><td>
            <form method='post'>";
            if($key = array_search($row['serialno'], $arraynosiri) !== false) {
                $checkbox = "checked";
            }
            else{
                $checkbox = "";
            }
            echo "<input type='checkbox' name='sBorrow' id='sBorrow' class='sBorrow' value='". $row['serialno'] ."' ".$checkbox.">
            </form></td></tr>";
            $startrow++;
            //echo $row['education_level'];


    }
    echo "</tbody>";
    echo "</table>";
}
else{
    echo "<p align='center'>Nothing to show you :( I am really sorry for this T_T </p>";
}

?>

<script type="text/javascript">
    $(document).ready(function() 
    { 
        $("#myTable").tablesorter();
        setsession(null,null);

    } 
    ); 
</script>

I use session and array to store the value of checked row so that it can be called to other php page.

<?php

session_start();
if(isset($_POST['sBorrow']) && $_POST['action']){



    if(isset($_SESSION['sBorrow']) && is_array($_SESSION['sBorrow'])){
        $sborrow = $_POST['sBorrow'];
        $set = $_SESSION['sBorrow'];
    }
    else{
        $set = array();
    }

    if($_POST['action'] == "SET"){
        array_push($set, $_POST['sBorrow']);
        $_SESSION['sBorrow'] = $set;

        //QUERY FOR SORTING TABLE????
    }
    else if($_POST['action'] == "UNSET"){
            $unset = $_SESSION['sBorrow'];
            if(($key = array_search($_POST['sBorrow'], $unset)) !== false) {
                unset($unset[$key]);
                $_SESSION['sBorrow'] = $unset;
            }
    }

}
//session_destroy();
if(isset($_SESSION['sBorrow']))
    echo count($_SESSION['sBorrow']);



?>




AngularJS multiple checkboxes doubts (Angular Material)

I'm trying to get multiple Angular Material checkboxes with the same ng-model. I have two problems: how to get default checked checkboxes, and how to make at least one of these checkboxes to be required. I tried with ng-checked, but then I can't POST the values through the form.

HTML

      <label for="inputPassword3" class="col-sm-2 control-label">Školski sat *</label>
      <div class="col-sm-10" >
        <span class="col-sm-2" ng-repeat="period in periods">
          <md-checkbox ng-model="form.periods[period]" ng-click="toggle(period, selected)">
            . sat
          </md-checkbox>
        </span>
      </div>

App.js

$scope.periods = [1,2,3,4,5,6,7,8,9,0]; /*broj sati*/
      $scope.selected = [2];
      $scope.toggle = function (period, list) {
        var idx = list.indexOf(period);
        if (idx > -1) {
          list.splice(idx, 1);
        }
        else {
          list.push(period);
        }
      };
      $scope.exists = function (period, list) {
        return list.indexOf(period) > -1;
      };

Please, help.




jQuery - Limit groups of labels and checkboxes to a max number

I'm trying to limit a max number selectable for checkboxes and their relative labels. Checkboxes work fine but labels are still selectable more than the limit.

My html input is formed like this:

<label id="b-<?php echo $term->term_id; ?>" class="btn btn-default <?php echo $labelchk ?>">
    <div class="bizcontent">
        <input id="youaresure" type="checkbox" name="email_cats[]" <?php echo $chk ?> value="<?php echo $term->term_id ?>" />
        <h5><?php echo $term->name ?></h5>
    </div>
</label>

and my jQuery to limit checkboxes and labels is like:

var $checkboxes = $('input[id="youaresure"]');
var $parent = $checkboxes.parent('label');
var max = 5;
$checkboxes.show();
$checkboxes.change(function () {
    $(this).prop('checked', function () {
        if ($(this).is(':checked')) {
            return ($checkboxes.filter(':checked').length <= max) ? true : false;
        }
    });
});
$parent.show();
$parent.change(function () {
    $(this).prop('class', function () {
        if ($(this).is('active')) {
            return ($parent.filter('active').length <= max) ? true : false;
        }
    }

Basically, php inserts an active class to labels parents of inputs:checked and I should prevent both labels and inputs to be selected if more than 5. For checkboxes is fine but parent labels are still selectable and basically are the visible ones.




Uncheck all checkboxes in AngularJS

I am having trouble finding a solution that allows me to simply uncheck all checkboxes using AngularJS. I use a simple ng-repeat to make checkboxes and want a button to clear them all.

        <div class="form-group">  <!-- Checkbox Group !-->
                    <label class="control-label">What are your requirements</label>
                    <div class="checkbox" ng-repeat="block in blocks">
                      <label>
                        <input type="checkbox" ng-model='myModel' name="block" value="block" ng-change="filter(block)">
                        
                      </label>
                    </div>
                </div>  

                <div> 
                    <input type="button" class="btn btn-primary " name="Clear" ng-click="reset()" value="Reset"> </input>
                </div>

I have tried altering the ng-model a few times, but keep getting errors since I use the ng-change function. Is there any way I can make a function called reset() in the controller to clear all the checkboxes (even if it is in a for loop iterating through each one by name)?

For referense

$scope.blocks = ["Lambda","Tokenization","Hadoop"];




vendredi 29 juillet 2016

Add a timer in a checkbox in C#

I've a C# program who allow to export data from a format (txt, dat ..) to another. To do this, the last step is to click on a Export button. I would like to add a timer in the export button, so export can be performed automatically each 18minutes. I'm working with following codes to try to display message when the box is checked:

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {

        do_checked();
    }

    private void do_checked()
    {
        buttonExportData.Enabled = checkBox1.Checked;
    }

    private class auto_export
    {
        private static System.Timers.Timer aTimer;

        private void MainForm()
        {
            // Normally, the timer is declared at the class level, 
            // so that it stays in scope as long as it is needed. 
            // If the timer is declared in a long-running method,   
            // KeepAlive must be used to prevent the JIT compiler  
            // from allowing aggressive garbage collection to occur  
            // before the method ends. You can experiment with this 
            // by commenting out the class-level declaration and  
            // uncommenting the declaration below; then uncomment 
            // the GC.KeepAlive(aTimer) at the end of the method. 
            //System.Timers.Timer aTimer; 

            // Create a timer with a 30 minutes (1200 second interval).
            aTimer = new System.Timers.Timer(1800000);

            // Hook up the Elapsed event for the timer.
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

            // Set the Interval to 18minutes (1080 seconds or 1080000 milliseconds).
            aTimer.Interval = 1080000;
            aTimer.Enabled = true;

            Console.WriteLine("Press the Enter key to exit the program.");
            Console.ReadLine();

            // If the timer is declared in a long-running method, use 
            // KeepAlive to prevent garbage collection from occurring 
            // before the method ends. 
            //GC.KeepAlive(aTimer);
        }

        // Specify what you want to happen when the Elapsed event is  
        // raised. 
        private static void OnTimedEvent(object source, ElapsedEventArgs e)

        {
            if (checkBox1.Checked == true)
            { Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime); }
        }

But, Visual Studio 2015 display errors: Severity Code Description Project File Line Error CS0120 An object reference is required for the non-static field, method, or property 'MainForm.checkBox1'




how to add multiple values from checkbox into .txt file

For a simple voting system, i put the values into a .txt file. This is the array i use:

$quickpolloptions = ['Mozilla', 'Chrome', 'Opera', 'IE', 'Safari'];

This is the form:

<form method="post" id="quickpoll">
   foreach ($quickpolloptions as $key => $value) {
         echo "<tr>";
             echo "<td>";
                    echo "<label>$value</label>";
         echo "</td>";
         echo "<td>";
                    echo "<input type='checkbox' name='checkboxvote[]' value='$key'><br>";
         echo "</td>";
      echo "</tr>";
    }
<input type="submit" value="Submit">
</form>

This is how i store the data:

$result_file = "data/vote_result.txt";

if (file_exists($result_file)) {
   $results = explode(',', file_get_contents('data/vote_result.txt'));
} else {
   // start with zeros if you don't have a file yet
   $results = array_fill(0, count($quickpolloptions), 0);
}

// below i am trying to read each value fromn checkbox and store in .txt file

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

  foreach ($_POST['checkboxvote'] as $checkbox) {
    $results[$_POST['checkboxvote']]++;
    file_put_contents('data/vote_result.txt', implode(',', $results));
  }
}

So i do not succeed in the last part: to put multiple values in the txt file.

How can i do that?




Using Knockout to update checked boxes and store selected values

I have a list a checkbox list which I want to be able to select and deselect all of the options, and store the selected values in a knockout array.

Here's my HTML

<a><span data-bind="click: selectAllUsers">SELECT ALL</span></a>
<a><span data-bind="click: deselectAllUsers">DESELECT ALL</span></a>
<ul data-bind="foreach: users">
      <li>
            <input type="checkbox" data-bind="checked: $parent.selectedUsers" />
            <span data-bind="text: name"></span>
      </li>
</ul>

And here's the section of my javascript:

var userData = //populated earlier
self.users = ko.observableArray([]);
self.selectedUsers = ko.observableArray([]);
self.selectAllUsers = function () {
    self.selectedUsers(userData)
}

self.deselectAllUsers = function () {
    self.selectedUsers([]);
}

When the view model is initialized, users and selectedUsers and both initialized to the array of user objects stored in userData. As it stands now, the checkboxes are not automatically checked and when I do check/uncheck one it affects all options in the checkbox. Ideally it would only change the selected checkbox and update selectedUsers.




filter selected checkbox item show in angular material chips

i want to show the filter selected checkbox item in the angular material chips

<h2 class="md-title">Use the default chip template.</h2>

<md-chips ng-model="items" readonly="readonly"></md-chips>


<div layout="column">
    <div flex><h2>Filter</h2></div>

    <div class="demo-select-all-checkboxes" flex="100" ng-repeat="item in items">
        <md-checkbox ng-checked="exists(item, selected)" ng-click="toggle(item, selected)">
            
        </md-checkbox>
    </div>
</div>




checkbox is not working when using onclick in angular controller

I am trying to use checkboxes in angular controller to show some places on google maps v3, but when I click the checkboxes, they are not working. It seems that the problem lies in onclick and performSearch function cannot be executed. I am new to angularjs, so I am not sure how to change the code in angular method. What should I do to make checkboxes effective? Any help is appreciated. Thanks in advance !

Here is what I want to achieve, but the code only works when not in angular controller.

http://ift.tt/2am2t4A

Here is part of code I tried in angular controller.

 var infowindow;
  var service;
  var transportMap;
  var markersArray = [];
  var options = ['train_station', 'bus_station', 'subway_station', 'transit_station', 'airport',
    'grocery_or_supermarket', 'hospital', 'movie_theater', 'restaurant', 'shopping_center', 'park', 'night_club', 'pharmacy', 'police', 'embassy', 'shopping_mall'
  ];

  $(document).ready(function() {
    initializeTransportMap();

  });

  function getLetteredIcon (letter) {
    return "http://ift.tt/JWeld1" + letter + ".png";
  }

  function initializeTransportMap() {
    var transportLatLng = {
      lat: $scope.result[1].data[0].Latitude,
      lng: $scope.result[1].data[0].Longitude
    };

    transportMap = new google.maps.Map(document.getElementById('transportMap'), {

      center: transportLatLng,
      scrollwheel: false,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      //   mapTypeId: google.maps.MapTypeId.HYBRID,
      mapTypeControl: true,
      disableDefaultUI: false,
      zoomControl: true,
      zoomControlOptions: {
        style: google.maps.ZoomControlStyle.LARGE,
        position: google.maps.ControlPosition.RIGHT_BOTTOM
      }
    });

    infowindow = new google.maps.InfoWindow();
    service = new google.maps.places.PlacesService(transportMap);


    var defaultMarker = 'http://ift.tt/2am256n';
    var marker = new google.maps.Marker({
      position: transportLatLng,
      map: transportMap,
      icon: defaultMarker,
      title: 'Hello World!'
    });
    google.maps.event.addListenerOnce(transportMap, 'bounds_changed', function() {
      $scope.performSearch
    });

    for (var i = 0; i < options.length; i++) {
      document.getElementById('options').innerHTML += '<input type="checkbox" id="' + options[i] + '" ng-click="performSearch()"> <img src=' + getLetteredIcon(String.fromCharCode('A'.charCodeAt(0) + i)) + ' height="20" /> ' + options[i] + '<br>';


    }

  }

  $scope.performSearch = function() {
    clearMaps();
    var clickedOptions = [];
    for (var i = 0; i < options.length; i++) {
      if (document.getElementById(options[i]).checked) {
        performTypeSearch(options[i], getLetteredIcon(String.fromCharCode('A'.charCodeAt(0) + i)));
      }
    }
  }

  $scope.performTypeSearch = function(type, icon) {
    var request = {
      //   bounds: transportMap.getBounds(),
      location: transportLatLng,
      radius: 5000,
      types: [type]
    };
    service.radarSearch(request, function(results, status) {
      if (status != google.maps.places.PlacesServiceStatus.OK) {
        alert(type + ":" + status);
        return;
      }
      for (var i = 0, result; result = results[i]; i++) {
        createMarker(result, icon);

      }
    });
  }

  $scope.createMarker = function(place, icon) {
    var marker = new google.maps.Marker({
      map: transportMap,
      position: place.geometry.location,
      icon: icon

    });
    markersArray.push(marker);

    google.maps.event.addListener(marker, 'click', function() {
      service.getDetails(place, function(result, status) {
        if (status != google.maps.places.PlacesServiceStatus.OK) {
          alert(status);
          return;
        }
        infoWindow.setContent(result.name);
        infoWindow.open(transportMap, marker);
      });
    });
  }

  $scope.clearMaps = function() {
    for (var i = 0; i < markersArray.length; i++) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }




Get Checkbox total count & save value in textbox if checked

I have written below code to get a total count of Checked chechbox and save the value checked value comma separated in textbox.

HTML:

<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='1' onchange='checkCount(this.value);'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='2' onchange='checkCount(this.value);'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='3' onchange='checkCount(this.value);'></label>

<input type="text" name="proId" id="proId">

JS:

function checkCount(elm) {
  var cheCount = $(":checkbox:checked").length;
  document.getElementById('selectCount').innerHTML = cheCount;

  definVal = document.getElementById('proId').value ;
  var inval = elm+","+definVal;
  document.getElementById('proId').value = inval;

  if(cheCount==0){
    document.getElementById('proId').value = "";
  }
}

Check the output in below image: enter image description here

My issue is that, when i unchecked the checkbox, its value is adding in textbox instead of getting remove.




ngModel remove the Checked status of checkbox automatically

I am using Angular to validate a checkbox and using ng-model for that:

<input type="checkbox" name="news1" value="news1" ng-model="news" <c:if test="${xxxx == yes'}">checked="checked"></c:if>>
<label ng-click="news1();"></label>

When the page where the checkbox is being embedded is called via a link which passes the status of the news1 (yes).. I mean if the user is laready registered for news1 or not. If it's so, the checkbox should be checked dynamically otherwise it's unchecked.

The problem is that when I use/add: ng-model="news1" as attribute in the checkbox, it doesn't work correctly. The checkbox is checked for seconds and it become unchecked suddenly.

In the controller I'm having the following function to change the status of the checkbox after the page has been loaded, so that the user can check and/or uncheck the checkbox:

$scope.news1 = function (){
    if(!$scope.news1){
        $scope.news1 = !$scope.news1;
    } else{
        $scope.news1 = !$scope.news1;
    }
};

The question, how can fix this so that the Checkbox keeps being checked when the status for news1 in the link is: yes. How can I prevent angular from setting the checkbox to unchecked automatically?

Thanks!




AngularJS - Checkbox cheked with ng-click after i checked with select all it check all but Clearing all is not clears all

AngularJS - Checkbox cheked with ng-click after i checked with select all it check all but Clearing all is not clears all

I have a list of objects in and Json array. I have declared the checkboxes with ng-repeat but when i check one and more checkboxes one by one it selects the checkbox and after that if i choose the part to select all for check all checkboxes with select all button it selects all also. But after i want to unselect all the array has no objects its true. But visualisation of checkbox is still checked why? Can anyone help me on this?

Here is the part of my coding about checkboxes

     var app = angular.module('myApp', []);
     app.controller('companyCtrl', ['$scope',
         function($scope) {
           $scope.addCompany = function(cmpid) {
             $scope.form.companies.push(cmpid);
           };
           $scope.Companies = [{
             "id": "001",
             "name": "Company1",
             "address": "Bla bla street, Somewhere City, Some Country"
           }, {
             "id": "002",
             "name": "Company2",
             "address": "Bla bla street, Somewhere City, Some Country"
           }, {
             "id": "003",
             "name": "Company3",
             "address": "Bla bla street, Somewhere City, Some Country"
           }, {
             "id": "004",
             "name": "Company4",
             "address": "Bla bla street, Somewhere City, Some Country"
           }, {
             "id": "005",
             "name": "Company5",
             "address": "Bla bla street, Somewhere City, Some Country"
           }, {
             "id": "006",
             "name": "Company6",
             "address": "Bla bla street, Somewhere City, Some Country"
           }];
           $scope.checkAll = function() {

             $scope.form.companies.splice(0, $scope.form.companies.length);
             $scope.all = true;
             for (var i in $scope.Companies) {
               $scope.addCompany($scope.Companies[i].id);
             }
             console.log($scope.form.companies);
           };

           $scope.uncheckAll = function() {
             $scope.form.companies.splice(0, $scope.form.companies.length);
             $scope.all = false;
             for (var i in $scope.Companies) {
               $scope.addCompany('');
             }

             console.log($scope.form.companies);

           };
         )
       ]
     };
<html>

<head>
  <script src="http://ift.tt/1oMJErh"></script>
  <script src="http://ift.tt/1mQ03rn"></script>
</head>

<body ng-app="myApp">
  <div>
    <a href="#" ng-click="checkAll()">Select All</a>
    <a href="#" ng-click="uncheckAll()">Clear All</a>
  </div>
  <ul>
    <li ng-repeat="cmp in Companies">
      <div ng-if="cmp">
        <input id="company-" type="checkbox" ng-model="cmp.Selected" ng-click="addCompany(cmp.id)" ng-value="cmp.id" ng-checked="all || cmp.Selected" />
        <label for="company-">
          <div class="title"></div>
        </label>
      </div>
    </li>
  </ul>
</body>

</html>



angular ng-disable checkbox not update with dynamic source

I have several checkboxes dynamicaly generated from array source:

        /*js*/
        $scope.arrondissements =   JSON.parse('
    [{"name":"4e","checked":false,"disable":true},  
    {"name":"5e","checked":false,"disable":false},  
    {"name":"11e","checked":false,"disable":false},  
    {"name":"12e","checked":false,"disable":false},  
    {"name":"13e","checked":false,"disable":false},  
    {"name":"14e","checked":false,"disable":false},  
    {"name":"15e","checked":false,"disable":false},  
    {"name":"16e","checked":false,"disable":false},  
    {"name":"17e","checked":false,"disable":false},  
    {"name":"18e","checked":false,"disable":false},  
    {"name":"19e","checked":false,"disable":false},  
    {"name":"20e","checked":false,"disable":false}]');


        <!-- HTML -->
        <div ng-repeat="item  in arrondissements" class="checkbox-inline ">
             <label>
             <input type="checkbox" ng-disabled=""
                      value="" ng-model="item.checked" >
              <span></span>
             </label>
        </div>

Checkboxes are generated correctly but When source gets updated , checkbox doesn't update

/*js*/
$scope.disableCb = function () {
      $scope.arrondissements[5].disable = true;
      $scope.arrondissements[6].disable = true;
      $scope.arrondissements[7].disable = true;
}

<!-- HTML -->
<button ng-click="disableCb()">disable</button>  

Could you tell me why and how to fix it?

I made a Plunker : http://ift.tt/2a4kq8Z




how to change a expression in a ngFor on a selection of checkbox angular 2

this is my html code

<tr *ngFor="let Resolution of Resolutions">
                        <td></td>
                        <td>
                        <div class="col-sm-10 ">
                            <div *ngFor="let Suggestion of Resolution.Suggestions">
                                <label >
                                    <input #t (change)="actualActions(t.checked)" type="checkbox" value="" checked="" class="i-checks"> 
                                </label>
                            </div>
                        </div>
                        </td>
                        <td><textarea value=""></textarea></td>
                    </tr>

first column will display some text and in the second column it will display checkboxes using another ngFor . when i select any of the checkboxes, in the third column i want to display whichever checkboxes are selected.

i know how to do this in jquery but not in Angular2 here when i am printing the selected values to the third column. all of the third column data is changing in the table i want checked values of the second column of each row to display in the third column of that perticular row




Angular 2 - Required field validation if checkbox is selected

Hy guys I'm new to Angular2 and in JS frameworks in general. I'm flowing tutorials on official site and haven't been able to find the solution to this problem.

So I have checkbox which is optional but if the checkbox is "checked" a new input field is shown. this part is not a problem. The problem is that I'm using modal based validation and I can't figure out how to make this new input field required only if the checkbox is checked.

this is may implementation so far:

<form [formGroup]="form" (ngSubmit)="onSubmit()">

<!---->

<div formGroupName="test">
    <div class="field">
        <div class="checkbox">
            <input type="checkbox" name="entryRecurring" value="" id="entryRecurring" formControlName="entryRecurring" />
            <label for="entryRecurring">
                <div class="checkbox_icon"></div>
                Recurring Entry
            </label>
        </div>
    </div>

    <div *ngIf="form.value.test.entryRecurring">
        <div class="field">
            <label for="entryRecurringAmount">Repeat Amount</label>
            <input type="text" name="entryRecurringAmount" value="" id="entryRecurringAmount" formControlName="entryRecurringAmount" />
        </div>
    </div>
</div>

<div class="field last">
    <button name="submit" id="submit" class="btn btn_sushi"  [disabled]="!form.valid">Submit</button>
</div>

    import {Component, Input, OnInit, OnChanges} from '@angular/core';
    import { Validators } from '@angular/common';
    import { REACTIVE_FORM_DIRECTIVES, FormGroup, FormControl, FormBuilder } from '@angular/forms';  
    import { FormMessages } from './../helpers/formMessages.component';
    import {EntriesService} from './entries.service';    
    import {ValidationService} from '../helpers/validation.service';
    import {Category, CategoryByType} from '../../mock/mock-categories';


    @Component({
        selector: 'entryForm',
        templateUrl: 'app/components/entries/entriesEdit.template.html',
        directives: [REACTIVE_FORM_DIRECTIVES, FormMessages],
        providers: [EntriesService, ValidationService]

    })
    export class EntriesEditComponent implements OnInit, OnChanges {
        @Input() control: FormControl;
        public form:FormGroup;
        public submitted:boolean = false;
        // private selectedId: number;

        categories: Category[];
        categoriesSortedByType: CategoryByType[];

        constructor(
            private _fb:FormBuilder,
            private _entriesService: EntriesService
            // private _router: Router
        ) {

            this.form = this._fb.group({

                test: this._fb.group({
                    entryRecurring: [''],
                    entryRecurringAmount: [''],
                })
            });
        }
onSubmit() {
        this.submitted = true;
        // console.log(this.form.value);

        if (this.form.dirty && this.form.valid) {
            this._entriesService.saveEntry(this.form.value);
        }
    }




jeudi 28 juillet 2016

How to check the boolean of checkbox?

I know this might sounds duplicate questions but none of them work for me. So far that i have done is getting the value but i want to know how to get the on/off value from the checkbox. I tried hidden field but i can't get the 1/0 value from the checkbox itself. All i get is the value.

My code is like this

$(document).delegate('.sBorrow', 'change', function(){
            var sBorrowClass = $(this).attr('class');
            var sBorrowValue = $(this).attr('value');
            var sBorrowName = $(this).attr('name');

            if(sBorrowClass.checked = true){
                alert(sBorrowValue);
                alert("unchecked");
            }
            else{
                alert(sBorrowValue);
                alert(sBorrowClass);
            }

For the checkbox form is like this

foreach($r as $row){
            $sBorrow = $_SESSION['sBorrow'];

            echo "<tr align='center'><td>". ($startrow+1) ."</td><td>". $row['matricno'] ."</td><td>". $row['studentname'] ."</td><td>". $row['programme'] ."</td><td>". $row['title'] ."</td><td>". $row['thesis_level'] ."</td><td>". $row['serialno'] ."</td><td>". $row['bavailable'] ."</td><td>
            <form method='post'>
            <input type='checkbox' name='sBorrow' id='sBorrow' class='sBorrow' value='". $row['serialno'] ."'>
            <input type='hidden' name='sBorrow' value=0 />
            </form></td></tr>";
            $startrow++;
            //echo $row['education_level'];

and questions 2.. Also how to make my checkbox remains checked when the user searching for more data after check the checkbox (Livesearch Ajax). Should i use localStorage or SESSION to store the value up until the user refresh?




The simplest method to POST a single on or off value (PHP)

This should be SO simple so I must be doing something wrong but I have a single checkbox to check whether a value is on or off

<input type="checkbox" name="highlight">

and when it is posted, if it is checked I get the value 'on' but if it is not checked I get an error

Notice: Undefined index: highlight 

Now I have tried testing whether it is empty or !isset but I would like to know if this is the correct method for passing a boolean value, it seems a bit convoluted.




Checkbox not updating value knockout js

I'm new at knockout js and feel I may not be understanding something here. I basically have a MVC checkbox, that when checked will update another field which is dependent on other field calculations. I can get the total amount field to update with respect to all of the other fields except for the checkbox, and I'm not sure what I'm doing wrong. I suspect that it's because I'm not passing in a self, but I'm not sure how I would pass that in with the conditional value in the final equation, but I'm not sure why that would be the case at all either. Maybe someone could shed some light on this.

I also noticed that if I made the calculations into variables and returned the final variable, the initial value would show correctly, but then nothing would make the final field update. Is there a reason this is the case or maybe I'm doing something wrong?

Here is the checkbox markup I'm using

<div class="form-group-sm">
    <label for="bookingType">International Property</label>
    <div class="checkbox">
        @Html.EditorFor(model => model.IsInternationalProperty, new { @id = "internationalProperty", @value = true, @data_bind = "checked: internationalProperty" })
        <label style="width: 200px; text-align: left">Select if it is outside the US</label>
    </div>
</div>

And here is my knockoutjs view model

var viewModel = function (data) {
    var self = this;
    self.internationalProperty = ko.observable();
    self.vendorBookingAmount = ko.observable(2.00);
    self.transactionFeesDue = ko.observable(0.00);
    self.transactionFeesWaived = ko.observable(0.00);
    self.iceBookingFees = ko.observable(0.00);
    self.vacationCashRedeemed = ko.observable(0.00);
    self.pointsDiscount = ko.observable(0.00);
    debugger;
    var international = (self.internationalProperty() == true) ? 0.05 : 0;

    self.memberBalance = ko.computed(function () {
        return (Number(self.vendorBookingAmount()) + Number(self.transactionFeesDue()) -
            Number(self.transactionFeesWaived()) + Number(self.iceBookingFees()) -
            Number(self.vacationCashRedeemed()) - Number(self.pointsDiscount())) +

            (Number(self.vendorBookingAmount()) + Number(self.transactionFeesDue()) -
            Number(self.transactionFeesWaived()) + Number(self.iceBookingFees()) -
            Number(self.vacationCashRedeemed()) - Number(self.pointsDiscount()))*international;
    }, self);
};

ko.applyBindings(new viewModel());




python 3.5 checkbox value not correct

I wrote a code in python 3.5 with tkinter and I'm having problems with getting the correct values from the current state (True/False) of the checkboxes. from some reason I don't always the correct value. This is my code: top = tk.Tk()

# build interface using 4 inputframes
inputFrame_video_rate = tk.Frame(top)
inputFrame_video_rate.pack()
inputFrame_video_rate.place(bordermode=tk.OUTSIDE, height=20, width=200, x=90, y=70)

inputFrame_video_output = tk.Frame(top)
inputFrame_video_output.pack()
inputFrame_video_output.place(bordermode=tk.OUTSIDE, height=20, width=400, x=90, y=100)

inputFrame_processing_info = tk.Frame(top)
inputFrame_processing_info.pack()
inputFrame_processing_info.place(bordermode=tk.OUTSIDE, height=20, width=400, x=90, y=130)

top.wm_title("Enter parameter details")
top.geometry("650x550")
label_video_rate = tk.Label(inputFrame_video_rate, text="video rate: ")
label_video_rate.pack(side=tk.LEFT)
entyr_video_rate = tk.Entry(inputFrame_video_rate, bd=2, width=50)
entyr_video_rate.insert(0, '10')
entyr_video_rate.pack(side=tk.LEFT)

label_video_output = tk.Label(inputFrame_video_output, text="output video file name:")
label_video_output.pack(side=tk.LEFT)
entry_video_output = tk.Entry(inputFrame_video_output, bd=2, width=50)
entry_video_output.pack(side=tk.LEFT)

label_video_output = tk.Label(inputFrame_video_output, text="")
label_video_output.pack(side=tk.LEFT)

# instruction
instructionsCheckBox = "Choose which skeleton to create (you can choose both)"
instructionsLabel = tk.Label(top, text=instructionsCheckBox, width=500, font=("Helvetica", 9))
instructionsLabel.pack()
instructionsLabel.place(x=15, y=130, width=400)


var_whole_body = tk.IntVar()
var_no_legs= tk.IntVar()
checkbox_whole_body = tk.Checkbutton(top, text = "Whole Body", variable = var_whole_body, \
                 onvalue = True, offvalue = False, height=5, \
                 width = 200)

show_skeleton_whole_body = var_whole_body.get()
print ('main before select: show_skeleton_whole_body')
print (show_skeleton_whole_body)

checkbox_whole_body.select()

show_skeleton_whole_body = var_whole_body.get()
print ('main after select: show_skeleton_whole_body')
print (show_skeleton_whole_body)


checkbox_no_legs = tk.Checkbutton(top, text = "  No Legs", variable = var_no_legs, \
                 onvalue = True, offvalue = False, height=4, \
                 width = 200)

show_skeleton_no_legs = var_no_legs.get()
print ('main before select: show_skeleton_no_legs')
print (show_skeleton_no_legs)

checkbox_no_legs.select()

show_skeleton_no_legs = var_no_legs.get()
print ('main after select: show_skeleton_no_legs')
print (show_skeleton_no_legs)

checkbox_whole_body.pack(side=tk.LEFT)
checkbox_whole_body.place(x=15, y=200, width=100)
checkbox_no_legs.pack(side=tk.LEFT)
checkbox_no_legs.place(x=15, y=250, width=100)

and this is the output I get from the prints:

main before select: show_skeleton_whole_body 0 main after select: show_skeleton_whole_body 0 main before select: show_skeleton_no_legs 0 main after select: show_skeleton_no_legs 0

for some reason the select() command didn't change the value from 0 to 1.

anybody knows what the problem is?

Thanks David




Drupal node form - how implement hierarchical checkboxes based on taxonomy tree

I can't fix one a very difficult problem for me.

I use drupal 7 and have a custom content type with a taxonomy field with 2 level hierarchy, the path /node/add/mycontenttype.

I know the beautiful module http://ift.tt/TpuzQc and it works perfectly! But for my project, I must use checkboxes instead of select list or drop-down.

I already tried override theme_hierarchical_select_select and dependents, however, the hierarchical_select has own JS which works with "select" only.

Also, I tried drupal ajax API, to rerender the taxonomy field, but it doesn't work if I am doing attachment to a form like

'#ajax' => array(
  'callback' => 'MYMODULE_ajax_callback',
  'wrapper' => 'replace_taxonomy_field',
 ),

in hook_form_alter()!

Any idea or any help?

Thank everybody in advance.




wpf checkbox label as button

In WPF I would like the label in the CheckBox to behave like a button, so when I toggle the checkbox to ON, I would like the label to change to a button, and when I toggle the checkbox to OFF, then button go change back to label.

Here is what I have so far

                            <CheckBox Margin="2,0,2,0"
                                        IsChecked="{Binding IsSteps}"
                                        HorizontalAlignment="Stretch"
                                        VerticalAlignment="Bottom"
                                        Height="32"
                                        FocusVisualStyle="{x:Null}"
                                        Style="{StaticResource SliderCheckBoxStyle}">
                                <CheckBox.Content>
                                    <TextBlock Text="Steps" Foreground="#FFFFFFFF" FontFamily="Lucida Sans" FontSize="8" FontWeight="Bold"/>
                                </CheckBox.Content>
                            </CheckBox>




How to make a google add to playlist style button with jQuery

I'm having trouble finding something that will bring me in the right direction.

When you are using YouTube you can add a video to a playlist, when you click that button it'll open a small menu of checkboxes and you can easily add more.

I want to create something similar but every search I do brings up a ton of jquery scripts for viewing playlists. I'm not entirely sure what this type of menu would be called.




simple yes or no checkbox for forms

I have inserted a checkbox in my form.

My code:

<input type="checkbox" id="checkbox" name="checkbox" value="1"/>

if($checkbox = ($_POST['checkbox']) == '1')
        {
            $checkbox = "si";
        }
        else
        {
            $checkbox = "no";
        }

I would like that if the checkbox is checked i receive "yes" otherwise "no". Thanks.




C# Devexpress How to code the CheckBox column header to select or deselect all

How to use C# code to program Devexpress gridView checkbox column header to show as check box, once it check or uncheck, it will select or deselect all the check box of the data row.

I already know how to program the check box below, i just could not find any clue to do the above. Need advise from all the master as i could.

Thank you, Brian

RepositoryItemCheckEdit repositoryCheckEdit1 = gridControl1.RepositoryItems.Add("CheckEdit") as RepositoryItemCheckEdit;
repositoryCheckEdit1.ValueChecked = "True";
repositoryCheckEdit1.ValueUnchecked = "False";
gridView1.Columns["Item"].ColumnEdit = repositoryCheckEdit1;




Python 3: PyQt: Make checkbox disabled + not grayed out + display tooltip

The only way I found to do this is here: How to make QCheckBox readonly, but not grayed-out. This, however, disables mouse interactions with the control. But I need the tooltip to be displayed when mouse is over the control. How can I achieve this?




Browser Doesn't Recognize Icons Of FontAwesome

There is a problem with me that the icons is not showing in the browser. I can not able to find out that my browser doesn't have the Fontawesome font but even not showing when Internet is connected Please anyone can help me for this.

.checkbox {
  padding-left: 20px; }
  .checkbox label {
    display: inline-block;
    position: relative;
    padding-left: 5px; }
    .checkbox label::before {
      content: "";
      display: inline-block;
      position: absolute;
      width: 17px;
      height: 17px;
      left: 0;
      margin-left: -20px;
      border: 1px solid #cccccc;
      border-radius: 0px;
      background-color: #fff;
      -webkit-transition: border 0.15s ease-in-out, color 0.15s ease-in-out;
      -o-transition: border 0.15s ease-in-out, color 0.15s ease-in-out;
      transition: border 0.15s ease-in-out, color 0.15s ease-in-out; }
    .checkbox label::after {
      display: inline-block;
      position: absolute;
      width: 16px;
      height: 16px;
      left: 0;
      top: 0;
      margin-left: -20px;
      padding-left: 3px;
      padding-top: 1px;
      font-size: 11px;
      color: #555555; }
  .checkbox input[type="checkbox"] {
    opacity: 0; }
    .checkbox input[type="checkbox"]:focus + label::before {
      outline: thin dotted;
      outline: 5px auto -webkit-focus-ring-color;
      outline-offset: -2px; }
    .checkbox input[type="checkbox"]:checked + label::after {
                content: "\f00c";
                font-family: 'FontAwesome'; }
    .checkbox input[type="checkbox"]:disabled + label {
      opacity: 0.65; }
      .checkbox input[type="checkbox"]:disabled + label::before {
        background-color: #eeeeee;
        cursor: not-allowed; }
.checkbox-primary input[type="checkbox"]:checked + label::before {
  background-color: #fff;
  border-color: #adadad; }
.checkbox-primary input[type="checkbox"]:checked + label::after {
  color: #fff; }
<div class="checkbox checkbox-primary">
        <input id="checkbox2" type="checkbox" checked="">
               <label for="checkbox2" >
                     Primary \f00c
               </label>
</div>
<i class="fa fa-camera-retro fa-lg"></i> fa-lg



display alert based on checkboxes displayed

I'm building a medication reminder app, and it works by user clicking a button and the system will display the medication the user should be taking based on the current time. And say if the user should take Med A and Med B at 3pm, and when user clicked the button at 3pm, two checkboxes with Med A and Med B will pop up, BUT if the user only checked "Med A", the system should display a message asking "why didn't you take Med B?" with a dropbox allowing the user to choose the reason.

However at the moment, if the user only checked "Med A", the system will display message asking "why didn't you take Med B and Med C" because Med C is also listed as one of the option for checkbox, just that it wasn't displayed as it should be taking at a different time. So it doesn't matter what medication the user should be taking at any particular time, the system will always ask based on all checkboxes options and not based on the current displayed checkboxes (which is displayed based on time).

JS:

function validate() {
        var msg = [];
        [].forEach.call(document.querySelectorAll('input[type="checkbox"]:not(:checked)'), function(elem, index) {
                        msg.push(elem.name);
                        });
                        navigator.notification.alert(msg.length ? 'Why didnt you take ' + msg.join(' and ') : 'Well done, you have taken all the medications!', alertDismissed, 'Message for you:','Done');

        }

    function showDiv(){
        if(document.querySelectorAll('input[type="checkbox"]:not(:checked)').length==0) {
            hide();
        }else{document.getElementById('welcomeDiv').style.display = "block";}
    }

    function myFunction(){
        var hour = (new Date()).getHours();
        showMed('A', hour == 15);
        showMed('B', hour == 15);
        showMed('C', hour == 19);
    }

    function showMed(med, show) {
        document.getElementById('med' + med).style.display = show ? '' : 'none';
    }

HTML

<div class="inner" id=text><button onClick="myFunction()" >Check</button></div>

</div>
    <div id=aa style="display:none">
        <form>
            <div id='medA'>
                <input type="checkbox" name="Med A" value="A">Medication A
            </div>
            <div id='medB'>
                <input type="checkbox" name="Med B" value="B">Medication B
            </div>
            <div id='medC'>
                <input type="checkbox" name="Med C" value="C">Medication C
            </div>

                <div id="welcomeDiv" style="display:none;" class="dropdown" title="Basic dialog">
                    <select>
                        <option value="" disabled="disabled" selected="selected">Please choose one</option>
                        <option value="forget">Forget to take</option>
                        <option value="notfeeling">Not feeling like taking it</option>
                        <option value="sideeffect">Worried about side-effects</option>
                        <option value="sideeffect">Run out of supplements</option>
                        <option value="misclick">Misclick</option>
                        <option value="others">Others</option>
                    </select>
                        <input id="btnbutton" class="btn" type="button" onClick="know();hide()" value="Submit">
                </div>
            <input id=xbutton type="button" onClick="validate();showDiv()" value="Submit">
        </form>




Toggle Checkbox if element has class

I ahve an list with elements, which get the class 'added' if clicked. This element shall be transferred to the form. Therefore I have made a list of checkboxes, which have the same classes as the 'li' from the list.

I wrote a jQuery script, which shall check, if the 'li' is clicked (hasClass) and then the proper checkbox should have the attribute 'checked'. But it is not working properly. Don't know what I have made wrong...

HTML:

<div class="container">
                    <div class="row row-centered konf-wrapper-1">
                        <div class="col-md-4 label-wrap">
                            <h1 class="header-label">Konzeption</h1>
                            <ul class="li-wrap">
                                <li class="added haken">Kommunikationsstrategie</li>
                                <li class="0 hide-me add-btn point">Zielgruppendefinition</li>
                            </ul>
                        </div>

                        <div class="col-md-4 label-wrap">
                            <h1 class="header-label">Kommunikationsmaßnahmen</h1>
                            <ul class="li-wrap">
                                <li class="1 hide-me add-btn point">Namensfindung & Logoentwicklung</li>
                                <li class="2 hide-me add-btn point">Exposé</li>
                                <li class="3 hide-me add-btn point">Textdesign</li>
                                <li class="4 hide-me add-btn point">Anzeigenkampagnen</li>
                                <li class="5 hide-me add-btn point">Außenwerbung</li>
                                <li class="6 hide-me add-btn point">Bautafelgestaltung</li>
                            </ul>
                        </div>
                    </div>

                    <div class="row row-centered konf-wrapper-2 label-wrap">
                        <div class="col-md-4 label-wrap">
                            <h1 class="header-label">Online-Marketing</h1>
                            <ul class="li-wrap">
                                <li class="8 hide-me add-btn point">Website</li>
                                <li class="9 hide-me add-btn point">Social Media</li>
                                <li class="10 hide-me add-btn point">Digitale Präsentation</li>
                            </ul>
                        </div>

                        <div class="col-md-4 label-wrap">
                            <h1 class="header-label">Virtuelle Welten</h1>
                            <ul class="li-wrap">
                                <li class="11 hide-me add-btn point">Innenvisualisierung</li>
                                <li class="11 hide-me add-btn point">Außenvisualisierung</li>
                                <li class="12 hide-me add-btn point">Virtuelle Begehung</li>
                                <li class="13 hide-me add-btn point">Augmented Reality</li>
                            </ul>
                        </div>
                    </div>
                     <button type="button" class="btn btn-primary added-btn" title="Zur Übersicht." id="gesamt-weiter" >Zum Formular</button>



                 </div> 

Checkboxes:

<div class="">
      <ul class="checker-wrap">
      <li><input type="checkbox" id="0" value="Zielgruppendefinition" class="0 checker" name="checkbox-group[]"></li>
      <li><input type="checkbox" id="2" value="Exposé" class="2 checker" name="checkbox-group[]"></li>
      <li><input type="checkbox" id="3" value="Textdesign" class="3 checker" name="checkbox-group[]"></li>
      <li><input type="checkbox" id="4" value="Anzeigenkampagnen" class="4 checker" name="checkbox-group[]"></li>
      <li><input type="checkbox" id="5" value="Außenwerbung" class="5 checker" name="checkbox-group[]"></li>
      <li><input type="checkbox" id="6" value="Bautafelgestaltung" class="6 checker" name="checkbox-group[]"></li>
      <li><input type="checkbox" id="8" value="Website" class="8 checker" name="checkbox-group[]"></li>
      <li><input type="checkbox" id="9" value="Social Media" class="9 checker" name="checkbox-group[]"></li>
      <li><input type="checkbox" id="10" value="Digitale Präsentation" class="10 checker" name="checkbox-group[]"></li>
      <li><input type="checkbox" id="11" value="Visualisierungen" class="11 checker" name="checkbox-group[]"></li>
     <li><input type="checkbox" id="12" value="Virtuelle Begehung" class="12 checker" name="checkbox-group[]"></li>
     <li><input type="checkbox" id="13" value="Augmented Reality" class="13 checker" name="checkbox-group[]"></li>
    </ul>
    </div>

jQuery:

var $check = $(".checker-wrap");
$(".add-btn").click(function() {
        var $li = $(this).toggleClass("hide-me added haken");

        var li_class = $(this).attr('class').split(" ");
        var $wrap = $li.closest('.label-wrap');
        // trigger checkbox for form
        if (($li).hasClass("added")) {
            $check.find('.'+li_class[0]).addAttr('checked');
        } else {
            $check.find('.'+li_class[0]).removeAttr('checked');
        }

        $wrap.find('h1').toggleClass('top-added', $wrap.find('.added').length > 0);
        });

So the question is, what do I have to change, that the checkboxes get triggered if the li has the class added, and if not, the checkbox should be unchecked...




Implement a different kind of CheckBox

Want to create something like this

I want to create check boxes like illustrated in the picture which can be uni-selected (only one of them gets selected) or multi-selected (multiple of them can be selected). How can this be best implemented?




mercredi 27 juillet 2016

How do you call a function with parameters using onclick?

I have a list of checkboxes that I want to display based on current time when user clicks a button.

JS:

var hour = (new Date()).getHours();
showMed('A', hour == 19);
showMed('B', hour == 19);
showMed('C', hour == 13);

function showMed(med, show) {
document.getElementById('med' + med).style.display = show ? '' : 'none';
}

HTML

<div class="inner" id=text><button onClick="showMed()">Check</button></div>
<form>
<div id='medA'>
<input type="checkbox" name="Med A" value="A">Medication A
</div>
<div id='medB'>
<input type="checkbox" name="Med B" value="B">Medication B
</div>
<div id='medC'>
<input type="checkbox" name="Med C" value="C">Medication C
</div>
</form>

I want the user to click the button and it will display the checkboxes based on the current time. But at the moment I can't seem to call the function




How to get value of checkbox from PHP and DOM

i need to know how on earth to get my checkbox value from PHP that is in a loop and also might be in DOM. I have to put that checkbox inside the loop to make it being shown on each row of databases. I tried to call it back using different method but none success. The last part is javascript but i don't have any clue how to do that.

My code for javascript index.php.

 function ajaxSearchUpdater(p){
        $("#result").show();
        var x = $("#search").val();
        var y = $("#edulevel").val();
        var pagelim = $("#pagefpe").val();
        var pagenumber = p;
        var checkb = $(".sBorrow").val()
        $.ajax({
            type:'POST',
            url:'userres.php',
            data:'q='+x+'&e='+y+'&pagelim='+pagelim+'&pageno='+pagenumber+'&checkb='+checkb,
            cache:false,
            success:function(data){
                $("#result").html(data)
            }
        });
    }



    $(document).ready(function(e) {
        ajaxSearchUpdater(1);               // fires on document.ready
        $("#search").keyup(function() {
            ajaxSearchUpdater(1);           // your function call
        });
        $("#edulevel").click(function() {
            ajaxSearchUpdater(1);           // your function call
        });
        $("#pagefpe").click(function() {
            ajaxSearchUpdater(1);           // your function call
        });
        $('.sBorrow').on('change', function(){
            var checkBorrow = $(event.target);
            var isChecked = $(checkBorrow).is(':checked');
            alert("test");
            alert(isChecked);
            alert('checkbox'+checkborrow.attr('id')+'is checked:'+isChecked);
        });
    });

    $(document).ready(function() {
      $('.sBorrow').on('change', function(event) {
        var checkbox = $(event.target);
        var isChecked = $(checkbox).is(':checked');
        alert('checkbox ' + checkbox.attr('id') + ' is checked: ' + isChecked);
      });
});

My code for the checkbox in PHP userres.php

if($stmt->rowCount() > 0){
    $r=$stmt->fetchAll();
    echo "<table class='tablesorter-blackice' id='myTable' style='width:97%; table-border: 1'>";
        echo "<thead>";
        echo "<tr>";
        echo "<th>No.</th>";
        echo "<th>No.Matric</th>";
        echo "<th>Name</th>";
        echo "<th>Programme</th>";
        echo "<th>Title</th>";
        echo "<th>Thesis Level</th>";
        echo "<th>Serial Number</th>";
        echo "<th>Availability</th>";
        echo "<th>Select book (Max 3)</th>";
        echo "</tr>";
        echo "</thead>";
        echo "<tbody>";

    foreach($r as $row){
            $sBorrow = $_SESSION['sBorrow'];

            echo "<tr align='center'><td>". ($startrow+1) ."</td><td>". $row['matricno'] ."</td><td>". $row['studentname'] ."</td><td>". $row['programme'] ."</td><td>". $row['title'] ."</td><td>". $row['thesis_level'] ."</td><td>". $row['serialno'] ."</td><td>". $row['bavailable'] ."</td><td>
            <form method='post'>
            <input type='checkbox' name='sBorrow' id='sBorrow' class='sBorrow' value='". $row['serialno'] ."'>
            </form></td></tr>";
            $startrow++;
            //echo $row['education_level'];
    }
    echo "</tbody>";
    echo "</table>";

I don't know what to do since i'm calling that page from ajax and uhh how should i explain this. You know index.php -> userres.php -> index.php using ajax. for javascript on the bottom part is what i have done and i dont think its right. I tried to create one other document ready for this checkbox but still even alert not showing up. I'm confused. please help T_T




disableing primefaces selectBooleanCheckbox using javascript

I try to disable a primefaces input component ditrectly in Javascript. It is about a p:selectBooleanCheckbox that should be disabled (and enabled) based on some other conditions (if certain value is filled in another p:inputText ...).

My environment looks like: - JSF Mojarra 2.2.7 - Primefaces 5.1 - PF Extensions 3.0.0 - Apache Tomcat 7.0.47

I've tried alredy a lot to do so - same things working for normal p:inputText are not working for the p:selectBooleanCheckbox.

JSF-Part:

   <p:selectBooleanCheckbox id="thing"
      widgetVar="thingWv"
      disabled="#{myBB.chkboxDisabled}"
      pt:pfId="thingChkBox"
      styleClass="thingy"
      itemLabel="The Thing"
      value="#{myBB.chkbox}" />

Javascript part for disbling:

   console.log ('disable the thing' );
   $('[pfId*=thingChkBoxLabel]').addClass("ui-state-disabled");
   $('[pfId*=thingChkBox]').addClass("ui-state-disabled");
   $('[pfId*=thingChkBox]').prop('disabled', true);
   $('[pfId*=thingChkBox]').attr('disabled', 'disabled');
   $('[pfId*=thingChkBox] > div > input').addClass("ui-state-disabled");
   $('[pfId*=thingChkBox] > div > input').prop('disabled', true);
   $('[pfId*=thingChkBox] > div > input').attr('disabled', 'disabled');
   $('[pfId*=thingChkBox] > div.ui-chkbox-box').addClass("ui-state-disabled");
   $('[pfId*=thingChkBox] > div.ui-chkbox-box').prop('disabled', true);
   $('[pfId*=thingChkBox] > div.ui-chkbox-box').attr('disabled', 'disabled');
   PF('thingWv').disable();

I've also tried some more js things didn't remember ... but now I don't know how to proceed.

Another way would be a and having in the disabled attribute some thing like #{myBB.othervalue > 5}. But I don't like this as it nneds another round tripp for this simple action.




How to delete multiple entries using Checkboxes? (PHP)

So i've been looking at a few resources on using multiple checkboxes as input. I'm building a PM system and want the user to be able to check off any message and then delete them with a button.

The problem is that whenever I check off any message(s):

A: You have to click the delete button twice.

B: Only the first message ever in the list ever gets deleted.

The button group:

<form method="post"
    <div class="button-group">
        <button type="submit" name="delete" class="delete button inbox">Delete</button>
        <button type="submit" name="mark" class="mark button inbox">Mark as Read</button>
    </div>

Later on the table rows:

<?php
    while ($row = mysqli_fetch_array($result)){?>
        <tr>
            <td><?php echo $row['PM_User1ID'];?></td>
            <td><?php echo $row['PM_User2ID'];?></td>
            <td><?php echo $row['PM_Subject'];?></td>
            <td><?php echo $row['PM_Timestamp'];?></td>
            <td>
                <label>
                    <input type="checkbox" name="check_list[]" value="<?php echo $row['PMID'];?>"><?php echo $row['PMID'];?>
                </label>
                </form>
            </td>
            <?php echo '<td><a name="'.$row['PMID'].'"href = "?link='.$row['PMID'].'">Reply</a></td>'; ?>
        </tr>
    <?php } ?>

And finally the Submit Post:

<?php
        if (isset ($_POST['delete'])){

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

                foreach($_POST['check_list'] as $selected){

                    $pmDelete = "DELETE FROM pm WHERE PMID = $selected"; 
                    $deletePM = $con->query($pmDelete);

                }
            }   
        }
    ?>

PM Page

GIF of issue




Javascript - passing dynamic recursive PHP value as javascript function

New to javascript. I have a while loop in PHP that looks like this

while ($row_voucher=mysql_fetch_row($risultato_query_voucher)) {    //INFO poche righe sotto, date_format da solo non funziona 
        echo "<tr>\n
                <td id=" . $row_voucher[3] ."><input type='checkbox' value='" . $row_voucher[3] . "' onchange='ControllaCodice(this)' id='" . $row_voucher[6] . "'></td>\n
                <td>" . $row_voucher[2] . "</td>\n
                <td>" . $row_voucher[3] . "</td>\n
                <td>" . date_format( new DateTime($row_voucher[4]), 'd/m/Y' ). "</td>\n
                <td>" . date_format( new DateTime($row_voucher[5]), 'd/m/Y' ). "</td>\n
                <td>" . $row_voucher[6] . "</td>\n
              </tr>\n";
      }

What i need to do is, when you click on the checkbox, to take the value of the first input type and add it. Since it's a while loop this will generate a table with a lot of checkboxes each one with a different value. So if you for example check 3 checkboxes the javascript I've written should take the 3 values and add it and then print it. If possible i'd need also to add the value on check and subtract it on uncheck.

Here's the not working javascript code:

<script type='text/javascript'>
   function ControllaCodice(this.value){
   window.alert(this.value);
   }
 </script>";

Thank you in advance.




How to get count of checkbox checked which has same value in dynamically created td?

Here i can select many check box's at same time And checkbox values may have duplicates. If check checkbox with same value twice need to get count as 2 and so on..

my table

echo '<tr style = "text-align:left"><td><input type = "checkbox" class = "selected_id_v" name = "selectd_prcs[]" value = '.$value->labdetail.'></td></tr>

what i tried

$(document).on('change','.selected_id_v',function () {
    if($(this).is(':checked'))
    {
     var checked val = $(this).val();
    }
});




How to create a checkbox around the entire div?

I am using jsp to create a webpage that would allow people to select multiple products by clicking on them (through a checkbox on top of them). The description, image etc etc is displayed through a database as a list onto the screen, each product in a separate div. My question is, how do i get to create a border around each of the divs and a checkbox somewhere along that border for each div (preferably a corner). my code snippet (i am using a bean for handling all connections etc):

 <div id="div1">   
    <%
        Set rs = Etn.execute("select * from products");
        while(rs.next()){
            %><div><%
        out.write(rs.value("id")+" ");
        out.write (rs.value("image_name")+"<br>");
        out.write(rs.value("image_actual_name")+" ");
        out.write(rs.value("product_type")+"<br><br>");
        %></div><%
        }

    %>    


 </div>




How to attach an input checkbox to a form (button_to)

I have two "button_to" tags (so they are forms)

= button_to("Validate", validate_contracts_path , {method: :patch, class: "bulk-selection"})
= button_to("Sign", sign_contracts_path , {method: :patch, class: "bulk-selection"})

and I have a checkbox collection below in a table, each checkbox represents a row, they are to perform bulk actions and the checkboxes are not included in the form.

td = check_box_tag "selected_records[#{record.id}]"

I would like to know if it is possible to attach the checkboxes when one of the buttons is clicked.

The more rails way the better, but it would be great too if it is achieve with JS

Thanks




CSS checkbox styling not working

I have my checkboxes and I am trying to style it with the following CSS

   input[type="checkbox"]{
display: none;
border: none !important;
box-shadow: none !important;
   }

      input[type="checkbox"] + label span {
display: inline-block;
vertical-align: middle;
width: 30px;
height: 30px;
background: url(/static/app/images/check_no.svg);

      }

     input[type="checkbox"]:checked + label span {
background: url(/static/app/images/check_yes.svg);
content: '';
color: #fff;
vertical-align: middle;
width: 30px;
height: 30px;
 }

The checkboxes are

     <div class="check1">
          <input id="id_contract_name" name="contract_name" type="checkbox"> 
          <label for=" id_contract_name "> 
              <span class="chk_contract"></span>   Name on Contract
          </label>
      </div>


     <div class="check2">
          <input id="id_is_ceo" name="is_ceo" type="checkbox"> 
          <label for=" id_is_ceo "> 
              <span></span>  CEO?
          </label>
      </div>

which are inside my form. This does not work when I click my checkbox. I am new to styling and let me know where the error is




Disable checkbox if value selected

I need a short jQuery code to do the following.

I got a dropdown like this:

<select id="pa_size">
<option value="32cm">32 cm</option>
<option value="52cm">52 cm</option>
</select>

And some other checkboxes under that dropdown.

Now my problem is: I want to disable the checkboxes IF the 52 cm option is selected. By default the checkboxes are enabled, and if returned to 32cm from 52cm it should be working again.




how can I disabled the checkbox and updated in database php

How can I disabled the checkbox and updated in the db? I mean, if the value is 1 the checkbox is checked and updated in the db, but if I unchecked the checkbox i want that in my db to be updated with 0.

   <input type="checkbox"  name="check" value = "$watered" <?php echo $check;?> OnClick="doAction(<?php echo $id;?>);" > </td>

the function doAction who doesn't matter and the file where is gone:

  if (isset($_GET['id'])) {

        $id = $_GET['id'];
        $query = mysql_query("update plants set watered = 1 where id = $id ");
        if ($query){
            echo "you have watered the plants.";
        }else {
            echo "you cannot watered the plants";
        }
    }else{
        echo "vvvvvvvvv";
}




mardi 26 juillet 2016

jquery combine filters instead of or

I have some jquery code for filtering with checkboxes which works fine, it loops through all the info I have and displays the correct filtered items, but I need it to combine the filters, at the moment it 'Or's through them. This is the jquery:

  var $filterCheckboxes = $('input[type="checkbox"]');

  function init(){
    $filterCheckboxes.on('change', function() {

var selectedFilters = {};

$filterCheckboxes.filter(':checked').each(function() {

  if (!selectedFilters.hasOwnProperty(this.name)) {
    selectedFilters[this.name] = [];
  }

  selectedFilters[this.name].push(this.value);

});

var $filteredResults = $('.card');

// loop over the selected filter name -> (array) values pairs
$.each(selectedFilters, function(name, filterValues) {

  // filter each .card element
  $filteredResults = $filteredResults.filter(function() {

    var matched = false,
      currentFilterValues = $(this).data('category').split(' ');

    // loop over each category value in the current .card's data-category
    $.each(currentFilterValues, function(_, currentFilterValue) {

      // if the current category exists in the selected filters array
      // set matched to true, and stop looping. as we're ORing in each
      // set of filters, we only need to match once

      if ($.inArray(currentFilterValue, filterValues) != -1) {
        matched = true;
        return false;
      }
    });

    // if matched is true the current .card element is returned
    return matched;

  });
});

$('.card').hide().filter($filteredResults).show();

});

}

init();




Checkbox in Kendo Grid - MVC 4

I want to add checkbox in my kendo grid. But when i use this code, it messed up my grid. My CRUD function didn't work at all and the checkbox is failed to be display too. This checkbox will be used to inserted the checked data into another table. In this code, i just want to make the checkbox appear without messing up my another function first. Please help me to solve this problem first. Thank you.

View

<div class="tables">
    <div class="table-responsive bs-example widget-shadow">
        <h4>Data Kuisioner:</h4>
            @(Html.Kendo().Grid<admission.Models.KuisionerPreviewModel>()
    .Name("grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.id_pertanyaan).ClientTemplate("<input type='checkbox' #= IsChecked ? checked='checked':'' # class='chkbx' onclick='checkMe(#= id_pertanyaan#, this)' />")
            .Width(64).HeaderTemplate("<input type='checkbox' id='masterCheckBox' onclick='checkAll(this)' />");

        columns.Bound(p => p.pertanyaan).Title("Pertanyaan");
        columns.Command(command => { command.Edit(); command.Destroy(); }).Width(250);
    })
    .ToolBar(toolbar => toolbar.Create())
    .Editable(editable => editable.Mode(GridEditMode.InLine))
    .Pageable()
    .Sortable()
    .Selectable(builder => builder.Mode(GridSelectionMode.Multiple).Type(GridSelectionType.Row))
    .Filterable()
    .HtmlAttributes(new { style = "height:570px;" })
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(10)
        .Events(events => events.Error("error_handler").Sync("sync_handler"))
        .Model(model => model.Id(p => p.id_pertanyaan))
        .Create(update => update.Action("kuisioner_Create", "Kuisioner"))
        .Update(update => update.Action("kuisioner_Update", "Kuisioner"))
        .Read(read => read.Action("kuisioner_read", "Kuisioner"))
        .Destroy(update => update.Action("kuisioner_Delete", "Kuisioner"))
    )
)
    </div>
</div>

<script type="text/javascript">
    function error_handler(e) {    
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function() {
                        message += this + "\n";
                    });
                }
            });        
            alert(message);
        }
    }

    function sync_handler(e) {
        this.read();
    }

    function checkMe(e, d) {
        var state = $(d).is(':checked');
        var grid = $('#grid').data().kendoGrid;
        $.each(grid.dataSource.view(), function () {
            if (this['parentId'] == e || this['Id'] == e) {
                if (this['IsChecked'] != state)
                    this.dirty = true;
                this['IsChecked'] = state;
            }
        });
        grid.refresh();
    }

    function checkAll(ele) {
        var state = $(ele).is(':checked');
        var grid = $('#grid').data().kendoGrid;
        $.each(grid.dataSource.view(), function () {
            if (this['IsChecked'] != state)
                this.dirty = true;
            this['IsChecked'] = state;
        });
        grid.refresh();
    }
</script>




How to get the value from a list of CheckBox in C#?

There are a list of CheckBox which is created in grammatically in C#. Then will be placed in a html table.

Those CheckBox are used for user to delete item(row). The amount of those CheckBox depends on the number of items in database and it is only a checkBox contained in one html table row.

Although i haven't finished with the html table creation from database yet, i want to know that is it possible to get the value from a list of CheckBox first.

Deleting item steps:

check all the item that you want to delete ==> click delete button ==> there is a method to delete those items fromdatabase (.aspx.cs).

Extra question.....

Does anyone know what is the best source to generate a html table? list, dataTable or other thing?




Display different checkboxes based on time of day

Hi all just wondering if its possible to display different checkboxes based on the current time. I'm building a medication reminder application, so the application will display different medication the user should take based on the current time. So for example at 1pm the checkboxes might displayed "medication A", "medication C". And at 9pm the checkbox might display "medication B".

This is what I have at the moment, but as you can see it will display the same checkboxes regardless of what the current time is.

<form>
<input type="checkbox" name="Med A" value="A">Medication A<br>
<input type="checkbox" name="Med B" value="B">Medication B<br>
<input type="checkbox" name="Med C" value="C">Medication C<br>
<input id=xbutton type="button" onClick="validate()" value="Submit">
</form>




C# ASP.NET Checkbox selected single value

I am trying to get selected value from my checkbox (talking about only single result/check), I want to get that value on event onClick on my button, and not only checkbox I also got there two dropdown lists that I am taking also selected value out of, and when I click my button, I get values from dropdown lists and I can't get value from checkboxlist and I dont know why because I set allready before on page load source and eveything seems to look fine but I can't get value :/

Here is the code:

 protected void btnSearch_Click(object sender, EventArgs e)
    {
       var dropDown_one= Convert.ToInt32(dropOne.SelectedValue); //THIS IS OK
       var dropDown_two = Convert.ToInt32(dropTwo.SelectedValue);//THIS IS OK
       var checkBox = Convert.ToInt32(checkBox.SelectedValue); //<- here I got error, because I am trying to convert "" value to int

    }

and on page load I dId this:

checkBox.DataSource =SomethingFromDatabase();
        checkBox.DataTextField = "Name";
        checkBox.DataValueField = "ID";
        checkBox.DataBind();

So I got values from Database and I am able to check them, but when I click my button I got error because checkboxlist says that its value is "" so like I did not select anything even if I did.. :/

Thanks guys, Cheers




using jquery in iframe child to check checkboxes by name

I have an iframe (same domain) that has a bunch of checkboxes on it. I'd like to have javascript run from the parent page and mark checkboxes in the child based on the name of the checkboxes (they have different values - but I'd like to check them all). The iframe's id and its name are both AppBody. All the checkboxes I care about are named dow0.




Child Checkboxes running code when Parent Checkbox is unchecked

I've got a set of parent checkboxes and children checkboxes, and each checkbox (parent or child), runs a piece of code. When I check the parent checkbox, the parent checkbox runs it's code, and the child checkbox doesn't. However, when I uncheck the parent checkbox, the child checkbox runs its code. Here's an example code:

HTML Code:
 <li>
        <input type="checkbox" onclick="validate()"  name="Parent" id="Parent">
        <label for="Parent">Parent</label>
        <ul>
            <li>
                <input type="checkbox" onclick="validate()"  name="Child" id="Child">
                <label for="Child">Child</label>
            </li>
 </ul>

 JavaScript code:
 $(function () {

$('input[type="checkbox"]').change(function (e) {
    var checked = $(this).prop("checked"),
        container = $(this).parent(),
        siblings = container.siblings();

    container.find('input[type="checkbox"]').prop({
        indeterminate: false,
        checked: checked
    });

    function checkSiblings(el) {
        var parent = el.parent().parent(),
            all = true;

        el.siblings().each(function () {
            return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked);
        });

        if (all && checked) {
            parent.children('input[type="checkbox"]').prop({
                indeterminate: false,
                checked: checked
            });
            checkSiblings(parent);
        } else if (all && !checked) {
            parent.children('input[type="checkbox"]').prop("checked", checked);
            parent.children('input[type="checkbox"]').prop("indeterminate", (parent.find('input[type="checkbox"]:checked').length > 0));
            checkSiblings(parent);
        } else {
            el.parents("li").children('input[type="checkbox"]').prop({
                indeterminate: true,
                checked: false
            });
        }
    }

    checkSiblings(container);
});
});

  var validate=function(){
    if(document.getElementById("Parent").checked){alert("Parent!");}   
    if(document.getElementById("Child").checked){alert("Child!");}   }