mardi 31 octobre 2017

Trying to zip and download multiple file directories PHP

I'm new to coding and i am trying to figure out how to zip and download multiple folders after selecting them via a series of check boxes.

However i keep getting the " ZipArchive::close(): Can't open file: Permission denied on line 21" whenever i try to run the code.

<?php

if (isset($_POST['dwnld'])) {
  //create ana array
  $ar=array();

  $checked=$_POST['dwnld'];

  for ($i=0; $i <count($checked) ; $i++) {
    $f="../Docs/".$checked[$i];
    $ar[$i]=$f;
  }

  $files = $ar;
  $zipname = 'file.zip';
  $zip = new ZipArchive;
  $zip->open($zipname, ZipArchive::CREATE);
  foreach ($files as $file) {
    $zip->addFile($file);
  }
  $zip->close();
}

?>

Any advise is welcomed.




Un-assign macros from all the checkboxes in Excel spreadsheet

I have an excel spreadsheet with more than 700 checkboxes. All the checkboxes have been assigned to one particular macro. I have deleted this macro. Now, I want to unassign this macro from all the checkboxes. I can do it for one checkbox manually by deleting the text when clicking on assign Macro. But how can I do this for large number of checkboxes? Any help greatly appreciated. Thanks!




unexpected javascript behavior in input type checkbox

I have an element in my asp.net core 2.0/mvc6 project which is an input of type checkbox. I was just testing how to change the value of another hidden element while toggling this checkbox and couldn't get it working, so I used the simple jquery that is shown to see what the click results were.

Html

<div class="col-xs-7 col-sm-8">
     <label class="css-input switch switch-sm switch-success">
          <input type="checkbox" id="validation-terms" name="validation-terms"><span></span> I agree to all terms
     </label>
 </div>
 <div class="col-xs-5 col-sm-4">
     <div class="font-s13 text-right push-5-t">
         <a href="#" data-toggle="modal" data-target="#modal-terms">View Terms</a>
      </div>
</div>
@Html.HiddenFor(m =>m.Terms, new { id="register-terms" })

Javascript

$terms is the variable for the element

//toggle the slider when terms modal agree button clicked
        $terms.on('click', function () {

            if ($terms.is(':checked')) {
                //$terms.prop('checked', false);
                //$('#register-terms').val(false);
                alert("changing to blank");
            } else {
                //$terms.prop('checked', true);
                //$('#register-terms').val(true); 
                alert("changing to green");
            }

        });

The page loads with the slider unchecked (blank, greyed out, whatever you want to call it) which is normal behavior unless you add the checked attribute. Upon clicking the checkbox (it is a slider) you would expect the javascript to detect it is unchecked and show the changing to green message, the behavior is the opposite! The first time you click it, you get the changing to blank message, the slider goes green, when you click it again, now it is in checked state (supposedly), you get the changing to green message and it goes back to blank.

What am I missing here?




Remove datagridview row on checkbox uncheck [duplicate]

This question already has an answer here:

i have 2 dgvws in 2 forms.On dgvw 1 , there's a checkbox column. If a user checks a row's checkbox it is immediately copied to the 2nd dgvw in form 2 . The code is :

  Private Sub userdatagrid_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles userdatagrid.CurrentCellDirtyStateChanged
    If userdatagrid.IsCurrentCellDirty Then
        userdatagrid.CommitEdit(DataGridViewDataErrorContexts.Commit)
        Dim c, t As Integer
        Selected.dg2.Columns.Clear()
        For t = 0 To userdatagrid.Columns.Count - 1
            Selected.dg2.Columns.Add(userdatagrid.Columns(t).Clone())
        Next
        For c = 0 To userdatagrid.Rows.Count - 1
            If userdatagrid.Rows(c).Cells(0).Value = True Then
                Selected.dg2.Rows.Add(userdatagrid.Rows(c).Cells(0).Value, userdatagrid.Rows(c).Cells(1).Value, userdatagrid.Rows(c).Cells(2).Value, userdatagrid.Rows(c).Cells(3).Value, userdatagrid.Rows(c).Cells(4).Value, userdatagrid.Rows(c).Cells(5).Value, userdatagrid.Rows(c).Cells(6).Value, userdatagrid.Rows(c).Cells(7).Value, userdatagrid.Rows(c).Cells(8).Value, userdatagrid.Rows(c).Cells(9).Value, userdatagrid.Rows(c).Cells(10).Value, userdatagrid.Rows(c).Cells(11).Value, userdatagrid.Rows(c).Cells(12).Value, userdatagrid.Rows(c).Cells(13).Value, userdatagrid.Rows(c).Cells(14).Value, userdatagrid.Rows(c).Cells(15).Value, userdatagrid.Rows(c).Cells(16).Value, userdatagrid.Rows(c).Cells(17).Value, userdatagrid.Rows(c).Cells(18).Value, userdatagrid.Rows(c).Cells(19).Value, userdatagrid.Rows(c).Cells(20).Value, userdatagrid.Rows(c).Cells(21).Value, userdatagrid.Rows(c).Cells(22).Value, userdatagrid.Rows(c).Cells(23).Value, userdatagrid.Rows(c).Cells(24).Value, userdatagrid.Rows(c).Cells(25).Value, userdatagrid.Rows(c).Cells(26).Value, userdatagrid.Rows(c).Cells(27).Value, userdatagrid.Rows(c).Cells(28).Value, userdatagrid.Rows(c).Cells(29).Value, userdatagrid.Rows(c).Cells(30).Value)
            Else
                For i As Integer = Selected.dg2.Rows.Count() - 1 To 0 Step -1
                    Dim row As DataGridViewRow
                    row = Selected.dg2.Rows(i)
                    Selected.dg2.Rows.Remove(row)
                Next
            End If
        Next
        Selected.dg2.Columns(0).Visible = False
    Else
    End If

My question is, suppose a user has checked a rows checkbox (which adds the row to the 2nd dgvw), then unchecks the it, i want to remove the just-added row from dgvw2 on checkbox uncheck...How to do so ?




mark more on check box and post it

I would like to mark one or two or all my checkbox and post.

This is my code

<div ng-repeat="person in unassigned">
<div class="col-xs-9 col-sm-12 unassigned">
    <label>
        <input type="checkbox" value=""> 
    </label>
</div>
</div>
<div>
<div type="button" ng-click="assign(person.id)">Save</div>
<div type="button" data-dismiss="modal">Close</div>
</div>

$scope.assignPlayer = function (id) {
    $http.post('api/teams/' + $scope.currentCity + '/person', JSON.stringify({ id: id }))
        .then(function (res) {
            location.reload();
            console.log(res);
        })
        .catch(function (err) {
            console.log(err);
        })
}

Any idea how can I do that

Thank you for help




Save checkbox value in a bootstrap modal and read & apply when revisiting

I read a lot of posts about saving cookie and reading from it but none has worked for me. I have a grid of 42 columns and I would like to achieve the following:

  • Be able to hide/show columns using checkboxes on a pop-up window (bootstrap modal) (achieved)
  • save the result in a cookie and read from it next time I visit the page.

What's different about my question is the way I populate those checkboxes which makes reading a cookie and applying .hide a little different:

$(document).ready(function () {

var shown = false;

//edit table button shows a bootstrap modal
$('#edit').click(function () {

//getting table headers
var headers = $('#entryTable thead th').map(function () {
    var th = $(this);
    return {
        text: th.text(),
        shown: th.css('display') != 'none'
    };
});

var h = ['<div id=\"tableEditor\"><table><thead>'];
$.each(headers, function () {

        h.push('<tr><th style=\"width:150px;\"><input class=\"box\" type=checkbox name=\"' + (j) + '\"',
               (this.shown ? ' checked ' : ' '),
               '/> ',
               this.text,
               '</th></tr>');


});
h.push('</thead></table></div>');

//show modal on #edit click and append the checkboxes into modal body
$('#myModal').modal('show');
$('#myModal').on('shown.bs.modal', function () {
    if(!shown)
        $('#myModal').find('.modal-body').append(h.join(' '));
    shown = true;
});

$('#checkAll').click(function () {
    $('input:checkbox').not(this).prop('checked', this.checked);
});

//apply .hide property to unchecked columns 
$('#Apply').click(function () {
    var showHeaders = $('#tableEditor input').map(function () { return this.checked; });
    $.each(showHeaders, function (i, show) {
        var cssIndex = i + 1;
        var tags = $('#entryTable th:nth-child(' + cssIndex + '), #entryTable td:nth-child(' + cssIndex + ')');
        if (show)
            tags.show();
        else
            tags.hide();
    });

    return false;
});

return false;
});

//saving in cookie
   $("input.box").each(function () {
    var myCookie = $.cookie($(this).attr('name'));
    if (myCookie && myCookie == "true") {
        $(this).prop('checked', myCookie);
    }
});
$("input.box").change(function () {
    $.cookie($(this).attr("name"), $(this).prop('checked'), {
        path: '/',
        expires: 365
    });
});
 function repopulateCheckboxes() {
    var checkboxvalues = $.cookie('myCookie');
    Object.keys(checkboxValues).forEach(function(element) {
        var cssIndex = i + 1;
        var tags = $('#entryTable th:nth-child(' + cssIndex + '), #entryTable td:nth-child(' + cssIndex + ')');
        if (show)
            tags.show();
        else
            tags.hide();
    });
}
repopulateCheckboxes();
});

I am sure of everything I do before the cookie part. It works perfectly but not sure how to do the rest. What am I doing wrong?

Thanks so much in advance




Dynamically changing property field in ExtJs Grid

I am using a grid with a checkbox and a combobox. Right now I am trying to find a way to make the combobox multi select if the checkbox is checked in roweditor.

            var pEditing =
            Ext.create('Ext.grid.plugin.RowEditing',
                    {
                        clicksToMoveEditor: 2,
                        errorSummary: false,
                        autoCancel: false,
                        listeners:
                        {
                            change: function (newValue, oldValue, eOpts)
                            {
                                if (newValue.value == true)
                                {
                                    this.down().down('grid').queryById('comboboxColumn').multiSelect = true;
                                }
                                else
                                {
                                    this.down().down('grid').queryById('comboboxColumn').multiSelect = false;
                                }
                                console.log("Checkbox Change Debug");
                             }
                        }
                   });

Grid creation code :

                                            {
                                                renderer: renderCheckbox,
                                                itemId: 'checkboxColumn',
                                                header: 'Checkbox',
                                                width: 100,
                                                sortable: false,
                                                dataIndex: 'ddCheckbox',
                                                editor: {
                                                    xtype: 'checkbox',
                                                    cls: 'x-grid-checkheader-editor',
                                                    listeners:{
                                                        change: function (newValue, oldValue, eOpts) {
                                                            pEditing.fireEvent('change',newValue, oldValue, eOpts);
                                                        }
                                                    },   
                                                },

                                            },
                                            {
                                                header: 'Speed',
                                                dataIndex: 'ddSpeed',
                                                itemId: 'comboBoxColumn',
                                                width: 125,
                                                editor:
                                                        {
                                                            xtype: 'combo',
                                                            editable: false,
                                                            multiSelect: false,
                                                            store:
                                                                    [
                                                                        ['1', '1'],
                                                                        ['2', '2'],
                                                                        ['3', '3'],
                                                                        ['4', '4'],
                                                                        ['5', '5']

                                                                    ]
                                                        }
                                            }

Right now the event is firing off and I can see the debug message printed to the log. However the multiselect property is not persisting after the event is fired. Is there any easy way to change the property of this combobox in the row? For example, if there are 3 rows in the grid, row one can have the checkbox checked, and multiple values selected while row two has the checkbox unchecked and only one selection can be made? I know I can find the index of the checkbox selected by using in the change function.

this.down().down('grid').getSelectionModel().getSelection()[0].getData()

Thanks




checkbox bindnig to bool causes application is in break mode

Fragment of my wpf

    <DataGrid x:Name="abonamenty_grid" AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="0,50,0,0" VerticalAlignment="Top" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Nabywca" Binding="{Binding nabywca}" Width="200" />
            <DataGridTextColumn Header="Odbiorca" Binding="{Binding odbiorca}" Width="200" />
            <DataGridTextColumn Header="Asortyment" Binding="{Binding czas_umowy_w_miesiącach}" Width="100" />
            <DataGridTextColumn Header="Kwota" Binding="{Binding kwota_abonamentu}" Width="*" />
            <DataGridCheckBoxColumn Header="Faktura auto" Binding="{Binding wystawiaj_automatycznie_fakturę}" Width="30" />
            <DataGridCheckBoxColumn Header="Fa auto na początku miesiąca" Binding="{Binding czy_fa_auto_na_początku_okresu}" Width="30" />
        </DataGrid.Columns>

Fragment of my query

                     select new
                     {
                         abonament_id = myabonamenty.id_abonament,
                         asortyment = nexotowary.Nazwa,
                         nabywca = nexonabywcy.NazwaSkrocona,
                         odbiorca = nexoodbiorcy.NazwaSkrocona,
                         wystawiaj_automatycznie_fakturę = myabonamenty.wystawiaj_automatycznie_fakturę,
                         czy_fa_auto_na_początku_okresu = myabonamenty.czy_fa_auto_na_początku_okresu,
                         kwota_abonamentu = myabonamenty.kwota_abonamentu
                     }).ToList();

TextColumn binding works but CheckBoxColumn binding. When displaing page with CheckBox binding application goes in break mode ( I have a window application is in break mode ). wystawiaj_automatycznie_fakturę,czy_fa_auto_na_początku_okresu are bool.




how to show checked checkbox based on database value in php

Here is my code:

<?php 
    $results = array();
    $cval = explode(',', $row['fruits']);

?>
<input type="checkbox" name="fruit[]" value="apple" <?php in_array('apple', $cval)?'checked':'' ?>>Apple
<input type="checkbox" name="fruit[]" value="banana" <?php in_array('banana', $cval)?'checked':'' ?>>Banana
<input type="checkbox" name="fruit[]" value="mango" <?php in_array('mango', $cval)?'checked':'' ?>>Mango
<input type="checkbox" name="fruit[]" value="pp" <?php in_array('pp', $cval)?'checked':'' ?>>PP
<input type="hidden" name="id" value="<?php echo $row['id']?>"><br>
<input type="submit" name="update" value="Update"> 

on print_r($cval) it gives : Array ( [0] => banana [1] => mango [2] => pp ) But checked is remain unchecked?

Whats the mistake? Help me




How to select all rows from Kendo grid using checkbox on header

I have select all checkbox on a kendo Grid. This check box only select first page and when you move to page to it is not selected. All i want is to use checkbox to select all the rows from the grid. If the rows returned on the grid are 500,all of them must be selected by one click which is the checkbox. I have tried lot of examples from but not getting it to work on MVC Razor.

I have tried many examples like this Example

@(Html.Kendo().Grid<Model>()
                .Name("Grid")
                .ToolBar(toolBar => toolBar.Template("<strong><a className='k-grid-toolbar-create' onClick='goToFunctionDownloadAllIpossFile()' href ='" + Url.Action("GetFileFromSession", "ConsolidatedPOSS", "https") + "?SeletectOrders=#= SeletectOrders#'" + "><button type='button' class='btn btn-primary'> Download Selected Orders </button></a></strong>"))
                .Columns(columns =>
                {
                columns.Bound(x => x.ordernumber).Title("Order Number");
                 columns.Template(@<text></text>).ClientTemplate("<input type='checkbox' id='chkId' #= selected ? checked='checked':'' # class='checkbox' />")
                .HeaderTemplate("<input type='checkbox' class='checkbox1' id='checkAll1' onclick='checkAll(this)'/>").Width(50);
                })
                .Pageable(pageable => pageable
                //.Refresh(true)
                .PageSizes(true)
                .ButtonCount(5))
                .Scrollable()
                .Filterable()
                .Sortable()
                .Resizable(resize => resize.Columns(true))
                .DataSource(dataSource => dataSource
                .Ajax()
                .PageSize(10)
                .ServerOperation(false)
                .Read(read => read.Action("Action", "Controller"))))

Javascript

function checkAll(ele) {
    alert();
    var state = $(ele).is(':checked');
    grid = $('#Grid').data('kendoGrid');

    datasource = grid.dataSource.view();
    //dataSource.pageSize(dataSource.total());
    $.each(grid.dataSource.view(), function ()
    {
        if (this['selected'] != state)
        {
            this.dirty = true;
        }  
        this['selected'] = state;
    });
    grid.refresh();
}




data-name attribute fetch row details in jquery

Here is a checkbox :

<input type="checkbox" data-name="TWIC Card" name="chkSP" id="chkSP8" value="8">
<label id="lblOut8" for="chkSP8" value="8">TWIC Card</label>

In jquery how can i checked true by using the data-name???

I am tried a lot code:

$("input[data-name='" + $.trim(SPArray[i]) + "']").prop("checked", "checked");
$("input[data-name='" + $.trim(SPArray[i]) + "']").attr("checked", "checked");
$("input[data-name='" + $.trim(SPArray[i]) + "']").attr('checked', true);

these are not working.

Can anyone tell me how can i get the details by data-name??

Important Note:-I want to fetch by only data-name features.

Here is my whole total code:

here is the input type :

<div class="check-box"><input type="checkbox" data-name="4' Tarps" name="chkSP" id="chkSP7" value="7"><label id="lblOut7" for="chkSP7" value="7">4' Tarps</label></div>

<div class="check-box"><input type="checkbox" data-name="TWIC Card" name="chkSP" id="chkSP8" value="8"><label id="lblOut8" for="chkSP8" value="8">TWIC Card</label></div>

 var SP="TWIC Card" ;
var SPArray = SP.split(',');
                            var allSelectedSP = "";
for (var i = 0; i < SPArray.length; i++) {
Array.from(document.querySelectorAll("input[data-name='" + SPArray[i].trim() + "']")).forEach(function (input) {
                                            input.checked = true;
                                        });
allSelectedSP += ", " + $.trim(SPArray[i]);
}




Getting the right Checkbox Value in Array

I have a form where i collect data from checkboxes. Here is my form

<div class="col-md-6">
                        <textarea name='description[]' placeholder="" rows='6' id='description' class='form-control '  
                     required  ></textarea> 
                     <div class="col-md-12">
                            <?php $meal = explode(",",$day->meal); ?>
                 <label class='checked checkbox-inline'>   
                <input type='checkbox' name='meal[]' value ='B'   class='' 
                @if(in_array('B',$meal))checked @endif 
                 />  </label> 
                 <label class='checked checkbox-inline'>   
                <input type='checkbox' name='meal[]' value ='L'   class='' 
                @if(in_array('L',$meal))checked @endif 
                 />  </label> 
                 <label class='checked checkbox-inline'>   
                <input type='checkbox' name='meal[]' value ='D'   class='' 
                @if(in_array('D',$meal))checked @endif 
                 />  </label>  
                                     </div> 

                                  </div> 

And this is my controller

$day = $_POST['day'] ;
            for($i=0; $i < count($day); $i++)
            {
                $dataDays = array(
                    'day'             => $_POST['day'][$i],
                    'title'           => $_POST['title'][$i],
                    'meal'            => implode(',', (array)$_POST['meal'] ),
                    'description'     => $_POST['description'][$i],
                    'cityID'          => $_POST['cityID'][$i],
                    'tourID'          => $id
                );
                \DB::table('tour_detail')->insert($dataDays);
            }

I get all the data right except meal. What am i missing with implode? I tried one without array as implode(',', $_POST['meal'] ), this didnt help. I tried implode(',', $_POST['meal'][$i] ) but i got an error. Can you please tell me how can i get the right data from checkboxes.

thanks




Get several checkboxes from view to controller in MVC 5

I have a view with multiple of checkboxes for the user to choose from, different options, but how can I get these either boolean values or ids' from these checkboxes back to the controller? I only get the checkboxes appear next to the value (a string of a department).

So when I click on any checkbox, really nothing goes back to the controller.

The simplest code is something like @Html.CheckBoxFor(model => item.Selected) e.g., and these under a foreach loop.




lundi 30 octobre 2017

Checkbox emoji that works well across mobile devices?

I'm creating a React Native application and I'm displaying some text in a web view. This web view contains interactive checkboxes. Initially I was using this checkbox but it looks broken on Samsung devices (at a small scale it doesn't look like anything).

So I'm wondering is there any other on/off checkbox emoji I could use and that would work across all devices?




Checkbox in accordion panel-body not working

I have a panel-group accordion div which contains multiple panels. For some reason when I put checkbox under panel-body it does not work.

<div class='row'>
    <div class='col-md-12'>
        <div class='panel-group' id='accordion' style='padding:0;'>       
            <div class='panel panel-default isSortablePanel'>
                <div class='panel-heading'>
                    <h4 class='panel-title'>
                        <a data-toggle='collapse' data-parent='#accordion' href='#collapseDiv'>
                            Header Content
                        </a>    
                        <div class='checkbox'>
                            <label><input id='garbageCheckbox' type='checkbox' value=''> Garbage Checkbox on Header (This one works) </label>
                        </div>
                    </h4>
                </div>
                <div id='collapseDiv' class='panel-collapse collapse'>
                    <div class='panel-body'>
                        <div class='row'>
                            <div class='col-md-12'>                         
                                <div class='checkbox'>
                                    <label><input id='garbageCheckbox' type='checkbox' value=''> Garbage Checkbox (This one does not work) </label>
                                </div>
                            </div>       
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

So the checkbox on accordion header works properly, but checkbox on panel-body does not work. Any idea?




Swap to select box once checkbox is checked

Checkboxes

I've got these set of checkboxes. They correspond to the days on which people are available for work. This system will be used to create a 'work schedule'. However, when the boss checks a checkbox (to have people work on that certain day), it should change to a select box so that the boss can tell where people will be working.

The checkboxes get their name in this way: {UserID}_[]. The value of the checkbox corresponds to the day in the week (Monday -> 0, Tuesday -> 1, Wednesday -> 2 etc.). The select box is made in this way: {UserID}_select_[].

I tried to use the following type of jquery script to get this working:

<script>
    var userList = <?php echo json_encode($userIdList); ?>;

    function swapInput(obj) {
        for (var i in obj) {
            $(document).ready(function() {
                $("input[name='" + obj[i] + "_[]']").change(function() {
                    if ($(this).prop('checked')) {
                        $(this).hide();
                        $('input[name="' + obj[i] + '_select_['$(this).val()']"]').show();
                    }
                }
            }
        }
    }

    swapInput(userList);

</script>

However, I'm quite new to jquery, so I might need some help there. I retrieve a php array from a database to get all the user ID's of which we have an availability. This one is converted to a jquery variable. I try to loop through that to get every single ID and make a line of code to hide the checkbox. Though.. it does not work.. as always...

When I var_dump the userIdList php variable, this is my result:

array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(4) }

This means the user ID's are 1, 2 and 4. But who can help me with the jquery part?




jquery setting checkbox state after preventing default action

I have a checkbox that needs to change state, but without invoking parent's click event. So, I created this:

    $("#divTabBody@(Model.TabNumber) tr input[type='checkbox']").on('click', function(e) { 
    e.preventDefault();
    e.stopPropagation();
    if($(this).is(':checked'))
        $(this).prop('checked', false);
    else
        $(this).prop('checked', true);
});

Parent's click is not execcuting, so that's good, but the checkbox is not changing state. Why?




Automatically toggle open filter dropdown based on checked checkboxes

I have a filter on a few checkboxes that have a status.

When the status is 'successful' then the URL changes and adds the successful status and only the items with that status will be displayed.

I am curious if I can have my filter automatically toggle open when I enter the page if the checkbox is checked for 'successful'.

    $scope.toggleFilters = true;
    $scope.toggleSuccessful = true;
    <p ng-click="toggleFilters=!toggleFilters">Toggle here</p>
    <div ng-hide="toggleFilters>
      <p ng-click="toggleSuccessful=!toggleSuccessful">
      Successful </p>
      <div ng-hide="toggleSuccessful">
         <input id="successful" type="checkbox" 
          ng-change="filterChanged()"
          ng-model="statusOptions.successful"/>
         <label for="successful">successful</label>
     </div>
   </div>

Can somebody give me a hint?




Vue how to set checked checbox if value is in array?

I have a little problem, because I have a component, where I have statuses to filtr and in value when someone check checbox I have id of this status. Like this: html:

 <div v-for="(status, key) in statuses">
                        <label v-bind:for="'status_id_'+key" class="form-check-label" v-on:click.stop>
                        <input type="checkbox"
                               v-bind:id="'status_id_'+key"
                               v-bind:value="key"
                               v-model="checkedStatusesIds"
                               v-on:click="updateStatus(key, $event.target.checked)"
                               class="form-check-input"/>
                            
                        </label>
                    </div>

And here is my Vue:

name: 'searchbox',
    data: () => ({
        query: undefined,
        checkedStatusesIds: [],
        statusesAll: false,
        searchError: '',
    }),
    props: [
        'placeholder',
        'statuses'
    ],

    methods: {
        getSearchResult: function () {
            if (typeof(this.statuses) !== 'undefined' &&
                this.checkedStatusesIds.length !== Object.keys(this.statuses).length) {
                this.statusesAll = false;
            }
            this.$emit('search', 1, this.query, this.checkedStatusesIds);
        },
        getQuerySearchResult: function () {
            this.searchError = '';
            if (typeof(this.query) === 'undefined' || this.query === '') {
                this.searchError = 'Too short query';
                return;
            }
            this.getSearchResult();
        },
        updateStatus: function (key, isChecked) {
            if (isChecked) {
                this.checkedStatusesIds.push(key)
            } else {
                let index = this.checkedStatusesIds.indexOf(key);
                if (index > -1) {
                    this.checkedStatusesIds.splice(index, 1);
                }
            }
            this.searchError = '';
            this.getSearchResult();
        },
        toggleStatuses: function (event) {
            let isChecked = event.target.checked;
            let self = this;
            this.checkedStatusesIds = [];
            if (isChecked) {
                Object.keys(this.statuses).forEach((value) => {
                    self.checkedStatusesIds.push(value);
                })
            }
            this.getSearchResult();
        },
    }

I have problem, because in data in checkedStatusesIds i have a structure for example like this:

0=>1
1=>2
3=>5

And I tryed to compare in my loop with statuses, or is in checkedStatusesIds, a specific key ( checkedStatusesIds.value = statuses.key ) them please let this checbox be checked. Be this doesn't work. How can I do this? I have every possible data to do this but I cannot programm this. Someone can help me?




How to add onChange method for uiselectmultiple element in angular-schema-form

I can add multiple items into a dropdown in angular schema form using the following schema and form.

var schema = {
    "type": "object",
    "properties": {
        "model": {
            "type": "string"
        }
    }
}

var form = [
    {
        key: "model",
        type: "uiselectmultiple",
        titleMap: {
            "Model 1", "model_1",
            "Model 2", "model_2",
            "Model 3", "model_3"
        },
        onChange: changeValues(modelValue, form)
    }   
];

onChange method doesn't fire when selecting an item from the list. Followed this solution and didn't get the expected result. http://ift.tt/2xyge9h

Anyone knows the answer for this problem. I can use checkboxes instead of using multi-selection. But how to remove the "X" mark, "+add" button and additional header text from the checkboxes.


var form = [
    {
        key: "comment",
        onChange: function(model, form){
            console.log('got there though');
        }    
    }
];



PHP different name checkbox array submit in data base

Please guide me how to grid loop from PHP different name checkbox array submit in data base?




dimanche 29 octobre 2017

XPATH for checkbox where id, type and name is same in Selenium

please look the Below code:

what will be the XPath for id= idConfirmedCheckbox?

<td class="tdCenter">
<input id="idConfirmedCheckbox" type="checkbox" onclick="return idConfirmedClicked(this);" name="idConfirmedCheckbox"/>
<input id="Customer_Person_Identifications_Identification_0_Confirmed" type="hidden" value="N" name="Customer_Person_Identifications_Identification_0_Confirmed"/>
<input id="Customer_Person_Identifications_Identification_0_NotConfirmedDisabled" type="hidden" value="" name="Customer_Person_Identifications_Identification_0_NotConfirmedDisabled"/>
</td>
<td class="tdCenter">
<input id="idConfirmedCheckbox" type="checkbox" onclick="return idConfirmedClicked(this);" name="idConfirmedCheckbox"/>
<input id="Customer_Person_Identifications_Identification_1_Confirmed" type="hidden" value="N" name="Customer_Person_Identifications_Identification_1_Confirmed"/>
<input id="Customer_Person_Identifications_Identification_1_NotConfirmedDisabled" type="hidden" value="" name="Customer_Person_Identifications_Identification_1_NotConfirmedDisabled"/>
</td>




Computing Total Value of Checkbox Selections

I am trying to figure out the best way to compute a total value based on selection of a combination of 5 different selections using checkboxes. Here is code example:

<input type="checkbox" value="Value 1" name="Value1" id="Value1">Value 1
<input type="checkbox" value="Value 2" name="Value2" id="Value2">Value 2
<input type="checkbox" value="Value 3" name="Value3" id="Value1">Value 3
<input type="checkbox" value="Value 4" name="Value4" id="Value1">Value 4
<input type="checkbox" value="Value 5" name="Value5" id="Value1">Value 5
<input type="checkbox" value="Total Value" name="TotalValue"
id="TotalValue">Total Value

Here are sample number values of the checkboxes: Checkbox 1 - 100 Checkbox 2 - 125 Checkbox 3 - 150 Checkbox 4 - 175 Checkbox 5 - 200

So my goal is to come up with a number value for TotalValue based on the checkbox selections. For example, if Checkbox 2 and Checkbox 4 are selected, Total Value would be 300. So user can select a single checkbox or any combination of checkboxes. I could probably do it using javascript, but the code would be very cumbersome and long. So was wondering if there is a streamlined way to do it using jQuery. Any help would be greatly appreciated. Thank you.




comparing the value with checkbox value in asp.net using vb.net

i am working on an assignment in which i have to fetch the data from ms access and fill the appropriate controls according to data.....i am facing a problem in checkbox....when i compare the single value with checkbox its working......but when i try to check multiple check boxes nothing happen...

here is the code ##(am using asp.net using vb)##

            If hobbies.Equals("cricket swimming tennis") Then
                CheckBox1.Checked = True
                CheckBox2.Checked = True
                CheckBox3.Checked = True
            ElseIf hobbies.Equals("cricket") Then
                CheckBox1.Checked = True
            ElseIf hobbies.Equals("swimming") Then
                CheckBox2.Checked = True
            ElseIf hobbies.Equals("tennis") Then
                CheckBox3.Checked = True
            End If

the first 'if' condition is not working ....'elseif' conditions are working




How to save a checkbox state in database in android

I am trying to save a checkbox state in my database and retrieve it later but it doesn't seem to work. I get now errors in my log and am hoping some one would be able to assist.

Here is my code for my checkbox:

 <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/check1"
        android:text="test"
        android:layout_below="@+id/textViewAge"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="15dp" />

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/check2"
        android:text="test2"
        android:layout_below="@+id/check1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="11dp" />

Then in my CreateOrEditJobCards.java:

checkA = (CheckBox) findViewById(R.id.check1);
    checkA.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            // TODO Auto-generated method stub
            if(checked)
            {
                SaveString="Yes";
            }
            else
            {
                SaveString="No";
            }
        }
    });
    checkB = (CheckBox) findViewById(R.id.check2);
    checkB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            // TODO Auto-generated method stub
            if(checked)
            {
                SaveStringA="Yes";
            }
            else
            {
                SaveStringA="No";
            }
        }
    });

......

if(personID > 0) {
        saveButton.setVisibility(View.GONE);
        buttonLayout.setVisibility(View.VISIBLE);

        Cursor rs = dbHelper.getPerson(personID);
        rs.moveToFirst();
        String personName = rs.getString(rs.getColumnIndex(DBHelper.PERSON_COLUMN_NAME));
        String personGender = rs.getString(rs.getColumnIndex(DBHelper.PERSON_COLUMN_GENDER));
        SaveString = rs.getString(rs.getColumnIndex(DBHelper.PERSON_CHECKBOX_A));
        SaveStringA = rs.getString(rs.getColumnIndex(DBHelper.PERSON_CHECKBOX_B));
        int personAge = rs.getInt(rs.getColumnIndex(DBHelper.PERSON_COLUMN_AGE));
        if (!rs.isClosed()) {
            rs.close();
        }

        nameEditText.setText(personName);
        nameEditText.setFocusable(false);
        nameEditText.setClickable(false);

        genderEditText.setText(personGender);
        genderEditText.setFocusable(false);
        genderEditText.setClickable(false);

        ageEditText.setText((personAge + ""));
        ageEditText.setFocusable(false);
        ageEditText.setClickable(false);

        checkA.setChecked(Boolean.parseBoolean(String.valueOf(SaveString)));
        checkA.setFocusable(false);
        checkA.setClickable(false);

        checkB.setChecked(Boolean.parseBoolean(String.valueOf(SaveStringA)));
        checkB.setFocusable(false);
        checkB.setClickable(false);
    }
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.saveButton:
            persistPerson();
            return;
        case R.id.editButton:
            saveButton.setVisibility(View.VISIBLE);
            buttonLayout.setVisibility(View.GONE);
            nameEditText.setEnabled(true);
            nameEditText.setFocusableInTouchMode(true);
            nameEditText.setClickable(true);

            genderEditText.setEnabled(true);
            genderEditText.setFocusableInTouchMode(true);
            genderEditText.setClickable(true);

            ageEditText.setEnabled(true);
            ageEditText.setFocusableInTouchMode(true);
            ageEditText.setClickable(true);

            checkA.setEnabled(true);
            checkA.setFocusableInTouchMode(true);
            checkA.setClickable(true);

            checkB.setEnabled(true);
            checkB.setFocusableInTouchMode(true);
            checkB.setClickable(true);


            return;
        case R.id.deleteButton:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.deletePerson)
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dbHelper.deletePerson(personID);
                            Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getApplicationContext(), JobCardMainActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // User cancelled the dialog
                        }
                    });
            AlertDialog d = builder.create();
            d.setTitle("Delete Job Card?");
            d.show();
            return;
    }
}

public void persistPerson() {
    if(personID > 0) {
        if(dbHelper.updatePerson(personID,
                nameEditText.getText().toString(),
                genderEditText.getText().toString(),
                checkA.getText().toString(),
                checkB.getText().toString(),

                Integer.parseInt(ageEditText.getText().toString()))) {

            Toast.makeText(getApplicationContext(), "Job Card Update Successful", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getApplicationContext(), JobCardMainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        else {
            Toast.makeText(getApplicationContext(), "Job Card Update Failed", Toast.LENGTH_SHORT).show();
        }
    }
    else {
        if(dbHelper.insertPerson(nameEditText.getText().toString(),
                genderEditText.getText().toString(),
                checkA.getText().toString(),
                checkB.getText().toString(),

                Integer.parseInt(ageEditText.getText().toString()))) {
            Toast.makeText(getApplicationContext(), "Job Card Inserted", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(getApplicationContext(), "Could not Insert Job Card", Toast.LENGTH_SHORT).show();
        }
        Intent intent = new Intent(getApplicationContext(), JobCardMainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
}
}

And in my DBHelper.java

public static final String PERSON_TABLE_NAME = "person";
public static final String PERSON_COLUMN_ID = "_id";
public static final String PERSON_COLUMN_NAME = "name";
public static final String PERSON_COLUMN_GENDER = "gender";
public static final String PERSON_COLUMN_AGE = "age";
public static final String PERSON_CHECKBOX_A = "checka";
public static final String PERSON_CHECKBOX_B = "checkb";

public DBHelper(Context context) {
    super(context, DATABASE_NAME , null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            "CREATE TABLE " + PERSON_TABLE_NAME +
                    "(" + PERSON_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    PERSON_COLUMN_NAME + " TEXT, " +
                    PERSON_COLUMN_GENDER + " TEXT, " +
                    PERSON_CHECKBOX_A + " TEXT, " +
                    PERSON_CHECKBOX_B + " TEXT, " +
                    PERSON_COLUMN_AGE + " INTEGER)"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + PERSON_TABLE_NAME);
    onCreate(db);
}

public boolean insertPerson(String name,
                            String gender,
                            String checka,
                            String checkb,
                            int age) {

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put(PERSON_COLUMN_NAME, name);
    contentValues.put(PERSON_COLUMN_GENDER, gender);
    contentValues.put(PERSON_COLUMN_AGE, age);
    contentValues.put(PERSON_CHECKBOX_A, checka);
    contentValues.put(PERSON_CHECKBOX_B, checkb);

    db.insert(PERSON_TABLE_NAME, null, contentValues);
    return true;
}

public int numberOfRows() {
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, PERSON_TABLE_NAME);
    return numRows;
}

public boolean updatePerson(Integer id,
                            String name,
                            String gender,
                            String checka,
                            String checkb,
                            int age) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(PERSON_COLUMN_NAME, name);
    contentValues.put(PERSON_COLUMN_GENDER, gender);
    contentValues.put(PERSON_COLUMN_AGE, age);
    contentValues.put(PERSON_CHECKBOX_A, checka);
    contentValues.put(PERSON_CHECKBOX_B, checkb);
    db.update(PERSON_TABLE_NAME, contentValues, PERSON_COLUMN_ID + " = ? ", new String[] { Integer.toString(id) } );
    return true;
}

public Integer deletePerson(Integer id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(PERSON_TABLE_NAME,
            PERSON_COLUMN_ID + " = ? ",
            new String[] { Integer.toString(id) });
}

public Cursor getPerson(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery("SELECT * FROM " + PERSON_TABLE_NAME + " WHERE " +
            PERSON_COLUMN_ID + "=?", new String[]{Integer.toString(id)});
    return res;
}

public Cursor getAllPersons() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "SELECT * FROM " + PERSON_TABLE_NAME, null );
    return res;
}
}

Basically in this app the user would select "add new jobcard" then would fill in the form and hit save. This then is displayed in a list view in number order. When the user would then select the form created earlier they can then hit send and it will then email the form (I am still working on that and code is not in above)

However like I said earlier, everything else in the form works and saves but can't seem to get the checkbox to save the state it was checked

Could some one please have a look at mu code and point out where I have gone wrong and assist?

Thanks




samedi 28 octobre 2017

Program having dropdown lists and checkboxes, prints statements based on which options were chosen?

I want to make a desktop program that has a bunch of dropdown lists and checkboxes, and based on the options I choose from the dropdown lists and which checkboxes are checked/ticked, the program prints out a desired set of outputs in the form of text statements.This set of outputs changes depending on what my inputs are.

Example Template:-
Dropdown1 has [option11, option12]
Dropdown2 has [option21, option22, option23]
Checkbox1 has [statementA that can be ticked or unticked]
Dropdown3 has [option31, option32]
"RUN button" to calculate results.


Outputs Logic:-
If [Dropdown1=11, Dropdown2=21, Checkbox1=TICKED, Dropdown3=31]
Print out [StatementX + StatementY]

If [Dropdown1=11, Dropdown2=21, Checkbox1=TICKED, Dropdown3=32]
Print out [StatementZ]

Etc... until all possible variations are defined.


Note that only one option must be picked for each dropdown list, and it should display the option I picked, otherwise display it as blank to indicate that I haven't picked any option yet. Also, the program should return an error if any dropdown list was left blank.
I only need the basic script that does this task EXACTLY, and I will be modifying the options and statements for my actual needs. Please also show me how to run the program, and how to modify it if this wasn't very obvious in the script. Any programming language is fine, but I prefer the program to be in Python/PyGTK or Java. Thanks! :)




React, Why label not firing onChange for checkbox?

I feel like I've done this a million times, but possibly not with a mapping function. I have a collection of activities that I'm creating checkboxes with the code is as follows (__map is coming from Lodash by the way):

<div className="activity-blocks">
{
    __map(this.state.activities, (activity, i) => {
        return (
            <div key={ i } className="single-activity">
                <input id={ `register-activity-${ i }` } 
                    type="checkbox" className="register-multiselect" 
                    name="main_activity" checked={ !!activity.checked } 
                    onChange={ (e) => this.toggleActivity(e, activity.id) }
                />
                <label htmlFor={ `register-activity-${ i }` }>{ activity.name }</label>
            </div>
         )
    })
 }

My onChange handler looks like this:

toggleActivity(e, activityId) {
    let activities = { ...this.state.activities };

    __forEach(this.state.activities, (activity) => {
        if (activityId === activity.id) {
            activity = __assign(activity, { checked: e.target.checked });
            return false;
        }
    });

    this.setState({ activities: activities });
}

The handler works just fine, it's for reference mostly. My issue is that the label is not firing the handler. I have tested only the checkbox input with no label and it fires off the handler. Does anyone know why the label is not doing so?

More info: I've had this problem before but it usually turns out to be an id mismatch or something simple like that. I don't believe so this time.




PHP retrieve unchecked checkboxes for array

I am getting ($_POST) different values comeing from checkboxes. (this row is repating N times)

<tr>
<td>All members <input type="hidden" name="group[]" value="0" /> <input type="hidden" name="project[]" value="<?php echo $_GET['id']; ?>" /></td>
                            <td align="middle"><input type="checkbox" rowid="0" columnid="1" name="read[]" value="1" <?php echo io($perm['read'],"checked"); ?>/></td>
                            <td align="middle"><input type="checkbox" rowid="0" columnid="2" name="open[]" value="1" <?php echo io($perm['open'],"checked"); ?> /></td>
                            <td align="middle"><input type="checkbox" rowid="0" columnid="3" name="comment[]" value="1" <?php echo io($perm['comment'],"checked"); ?> /></td>
                            <td align="middle"><input type="checkbox" rowid="0" columnid="4" name="edit[]" value="1" <?php echo io($perm['edit'],"checked"); ?> /></td>
                            <td align="middle"><input type="checkbox" rowid="0" columnid="5" name="mod[]" value="1" <?php echo io($perm['mod'],"checked"); ?> /></td></tr>

When I post them, I retrieve them with:

for ($i = 0; $i < count($group_array); $i++) {
                            $group = mysqli_real_escape_string($con,$group_array[$i]); [...]

The problem is that if a checkbox input is not checked, it is not added in the array.

So does anyone know how I could manage this situation?

A radio input would be perfect (I would have a value posted in any case... but with checkbox, it is yes or no. And as I have them stored as an array, I can't manage them one by one)




Access Violation at module project1.exe

i have a problem to this code :

Form1->ADOQuery2->SQL->Clear();
Form1->ADOQuery2->SQL->Add("SELECT * FROM setting WHERE item = 'use'");
Form1->ADOQuery2->Open();
String use = Form1->ADOQuery2->FieldByName("color")->AsString;
if(use == "1")
  cbKupon->Checked = true;
else
  cbKupon->Checked = false;

i get error "access violation at module project1.e x e" when i try to checked/unchecked checkbox based value of 'use'

How to fix it ?




values from unchecked checkboxes are also inserted into database

i have problem while making my application in windows form csharp regarding my checkbox in datagridview when i 1st time insert the value with options selected in checkbox it gets inserted fine in the database but on the 2nd time when i insert the value with new items checked in checked boxes and old ones unchecked it adds the new one along with the old ones which are unchecked. My code for your kind information and Help

protected void btnAssign_Click(object sender, EventArgs e)
    {
        int trainer;
        List<tbl_Trainer_Workshop_Mapping> ls = new List<tbl_Trainer_Workshop_Mapping>();

        int workshopid = Convert.ToInt32(dataGridViewtbl_Workshop.CurrentRow.Cells["UsWorkShopId"].Value.ToString());

        foreach (DataGridViewRow row in dataGridViewSelectTrainer.Rows)
        {


            if (row.Cells[0].Value == null)
            {
                row.Cells[0].Value = false;
            }
            else
            {
                trainer = Convert.ToInt32(row.Cells[1].Value.ToString());
                tbl_Trainer_Workshop_Mapping twm = new tbl_Trainer_Workshop_Mapping()
                { WorkShopId = workshopid, TrainerID = trainer };
                ls.Add(twm);
            }
        }


        if (ls.Count() > 0)
        {
            WorkshopBusiness Wb = new WorkshopBusiness();
            Wb.AssignTrainersToTheWorkShop(ls);
        }

        foreach (DataGridViewRow row1 in dataGridViewSelectTrainer.Rows)
        {
            row1.Cells[0].Value = false;
        }

    }

1st time when two options(value 1& 2) checked and shown in database against workshop id 4

Values entered in the database correctly for the 1st time

but on 2nd time it adds the value checked in the checkbox along with the options with are unchecked

Only one option (value 3) checked and the other two (value 1 & 2) unchecked

In DB one required is there along with the two which are not required

please guide regards




vendredi 27 octobre 2017

Centering a checkbox

I can't completely (only the label is centered when I try) center this checkbox to my 'card', how can I do it ?

I tried <center>...</center> and other CSS found on Stack Overflow but no one I found are working, so I ask help here.

Source : http://ift.tt/2yU4Fe7

Code :

<div class="checkbox">
    <label>
        <input type="checkbox" value="">
        <i class="input-helper"></i>
        Don't forget to check me out
    </label>
</div>

Current CSS : http://ift.tt/2yX5LI1

Thanks in advance.




Angular 1.6. Checkbox and Json data from database. How to get angular to show checked if in Json data?

I've been trying to look at how to represent checkbox in angular. I receive data from data base the example is : { ID: 27, ReportID: 1, CategoryID: 3, QuestionID: 23, Answer: {checkbox: {Text: "some text", data: {0: "User tasks", 1: "Scenarios"}}}

Now if we look at this then we see the "data" is the values I get from the database and there might be a lot of options that are left out since they were not checked when the record was sent to the database.

The code in the html that I've been trying to get to work with this is.

<label class="checkbox-inline">
    <input ng-model="reportInfo.Answer[question.ID]['checkbox']['data'][$index]" type="checkbox" ng-true-value="''" ng-false-value="''" ng-init="reportInfo.Answer[question.ID]['checkbox']['data'][$index]['checked'] = answerValue(ans, 'checkbox', 'data', ch.Choice)" >  
</label>

The reportInfo is empty in controller and the [*] is used to build up the json either if in edit or just making a new report. The answerValue is a function that is looking for values of existing answers or prepered records that are empty. looking like this.

$scope.answerValue = function (data, type, attribute, choice) {
    if (angular.equals({}, data.Answer)) {
        if (type == 'num')
            return 0; 
        else
            return '';
    }
    else {
        if (type == 'num')
            return data.Answer.number;
        else if (type == 'text')
            return data.Answer.text;
        else if (type == 'yesno')
            return data.Answer.yesno;
        else if (type == 'radio')
            return data.Answer.radio;
        else if (type == 'conditionalyesnotext') {
            if (attribute == 'radio')
                return data.Answer.conditionalyesnotext;
            else if (attribute == 'Text') {
                if (angular.equals({}, data.Answer.Text))
                    return '';
                else 
                    return data.Answer.Text.conditionalyesnotext;
            }
            else if (attribute == 'Textbox') {
                if (angular.equals({}, data.Answer.Textbox))
                    return '';
                else 
                    return data.Answer.Textbox.conditionalyesnotext;
            }
        }
        else if (type == 'checkbox') {
            if (attribute == 'data') {
                if (angular.equals({}, data.Answer.checkbox.data))
                    return '';
                else {
                    angular.forEach(data.Answer.checkbox.data, function(value, key) {

                      if ( value == choice) {
                        console.log(data.Answer.checkbox.data)
                      console.log(key + ': ' + value +' : ' + choice);
                        return true;
                      }
                    });
                }
            }
            else if (attribute == 'Text') 
                return data.Answer.checkbox.Text;
            else 
                return '';
        }
        else
            return  '';
    }
}

I've been looking into this and what ever I try to do. I can't get the checkboxes checked if the data exists in the json object.

Any idea on how I can solve this...

Thanks

=B




JAVA GUI - itemStateChanged

We have a couple of checkboxes and if any of them is selected we want to do something (say show a label on screen). I am reading this book and it suggests the following code but compiler gives the error "checkBox cannot be resolved to a variable".

Question 1- How can I solve this? Question 2- What's the difference between getItem and getSource methods of ItemEvent objects? (where to use which?).

public void itemStateChanged(ItemEvent ie) {
    if( ie.getItem() == checkBox)) { //the book's suggestion but it doesn't work
        if(ie.getStateChange() == ItemEvent.SELECTED) {
            // statements that execute when the box is checked

        } else {
                // statements that execute when the box is unchecke

        } 


     } else {
             // statements that execute when the source of the event is
             // some component other than the checkBox object
     }

 }




Datagrid checkbox logic to update table when checked

I am having difficulties in getting my checkbox column to work. What I am trying to achieve is to have the checkbox checked when the app loads if the condition matched a value from the table and send an update command to the database every time the checkbox gets checked or unchecked.

How should I write it to get it off the ground? I am looking to achieve my goal without MVVM. I would be grateful if someone can help me get unstuck.

This is how far I have got:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Audited" >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox x:Name="cBox" Checked="DataGridCheckBoxColumn_Checked" Unchecked="DataGridCheckBoxColumn_Unchecked"
              IsChecked="{Binding Audited, UpdateSourceTrigger=PropertyChanged}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <CheckBox x:Name="cBox" Checked="DataGridCheckBoxColumn_Checked" Unchecked="DataGridCheckBoxColumn_Unchecked"
              IsChecked="{Binding Audited, UpdateSourceTrigger=PropertyChanged}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Binding="{Binding Location}" Header="Location" Visibility="Collapsed"/>
        <DataGridTextColumn Binding="{Binding Date, StringFormat=MM-dd-yy}" Header="Date"/>
    </DataGrid.Columns>
</DataGrid>

xaml.cs

 public MainWindow()
        {
            InitializeComponent();

            string connectionString = "datasource=; Port=; Username=; Password=";
            string sMonth = DateTime.Now.ToString("MM");
            string sYear = DateTime.Now.ToString("yyyy");
            string sDate = DateTime.Now.ToString("yyyy-MM-dd");

            MySqlConnection connection = new MySqlConnection(connectionString);

            MySqlCommand Audit = new MySqlCommand("Select Audited from Daily.Table where MONTH(Date) = @sMonth AND YEAR(Date) = @sYear", connection);
            Audit.Parameters.Add(new MySqlParameter("sDate", sDate));

            try
            {
                connection.Open();

                MySqlDataReader AuditR = Audit.ExecuteReader();

                while (AuditR.Read())
                {
                    if (AuditR["Audited"] != DBNull.Value)
                    {
                        //How can set the checkbox to checked?
                    }; 
                }

                AuditR.Close();
                AuditR.Dispose();


        private void DataGridCheckBoxColumn_Checked(object sender, RoutedEventArgs e)
        {
            string connectionString = "datasource=; Port=; Username=; Password=";

            MySqlConnection connection = new MySqlConnection(connectionString);
            MySqlCommand AuditUpdate = new MySqlCommand("update Daily.Table set Audited='"Yes"' where ID= '" + this.txtID.Text + "'", connection);
            CheckBox checkBox = sender as CheckBox;

            //How can I mark the checkbox as checked from here?

        }

        private void DataGridCheckBoxColumn_Unchecked(object sender, RoutedEventArgs e)
        {
            string connectionString = "datasource=; Port=; Username=; Password=";

            MySqlConnection connection = new MySqlConnection(connectionString);
            MySqlCommand AuditUpdate = new MySqlCommand("update Daily.Table set Audited=NULL where ID= '" + this.txtID.Text + "'", connection);
            CheckBox checkBox = sender as CheckBox;

            //How can I mark the checkbox as unchecked from here?
        }




how to bind checkboxes to a hierarchical treeview in WPF, using a MVVM design pattern

I would like to get some direction on how to bind checkboxe to each treeview's item (populated from an SQL DB) in such a way that when a stand-alone checkbox placed outside the treeview is ticked, all the treeview items containing, e.g: abc as the first three characters will be ticked. Following this, the selected threeview's items will be added into an array.

So far, I have a hierarchical Data template containing the treeview's items, as can be seen below. enter image description here

Below is the relevant code:

MainWindow.xaml

<Window x:Class="DB.MainWindow"
    xmlns="http://ift.tt/o66D3f"
    xmlns:x="http://ift.tt/mPTqtT"
    xmlns:d="http://ift.tt/pHvyf2"
    xmlns:mc="http://ift.tt/pzd6Lm"
    xmlns:local="clr-namespace:DB"
    mc:Ignorable="d"
    Title="DB" Height="350" Width="645.022"
      WindowStartupLocation="CenterScreen" Background="Gainsboro">
<Window.DataContext>
    <local:TreeViewModel></local:TreeViewModel>
</Window.DataContext>


<TreeView ItemsSource="{Binding Tree.Items}" Margin="0,0,421,0">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:DbViewModel}" ItemsSource="{Binding Children}">
            <StackPanel Orientation="Horizontal">
                <CheckBox Focusable="False" IsChecked="{Binding IsChecked}" VerticalAlignment="Center"/>
                <TextBlock Text="{Binding Name}"></TextBlock>
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView> </Window>

DBViewModel.cs

 public class DbViewModel 
{
    public DbViewModel()
    {
        Children = new ObservableCollection<DbViewModel>();
    }
    public string Id { get; set; }
    public string Name { get; set; }
    public ObservableCollection<DbViewModel> Children { get; set; }
}

 public class TreeViewModel
{
    public TreeViewModel()
    {
        BuildTree();
    }

    public TreeViewModel Tree
    {
        get { return this; }
    }

    private void BuildTree()
    {
        string connectionString = GetConnectionString();
        using (var connection = new SqlConnection(connectionString))
        {
            // Connect to the database then retrieve the schema information.
            connection.Open();

            // Get the schema information of Databases in your instance
            DataTable databasesSchemaTable = connection.GetSchema("Databases");


            Items = new ObservableCollection<DbViewModel>();
            var rootNode = new DbViewModel
            {
                Name = "Databases",
                Children = new ObservableCollection<DbViewModel>()
            };
            Items.Add(rootNode);

            IEnumerable<string> databases = GetNameList(databasesSchemaTable.Rows, 0);

            foreach (string dbName in databases)
            {
                var dbNode = new DbViewModel { Name = dbName };
                rootNode.Children.Add(dbNode);
                if (dbName.ToUpper().Equals("<yourdatabase>"))
                {
                    DataTable table = connection.GetSchema("Tables");
                    IEnumerable<string> tables = GetNameList(table.Rows, 2);

                    var tableNode = new DbViewModel { Name = "Tables" };
                    dbNode.Children.Add(tableNode);
                    foreach (string tableName in tables)
                    {
                        tableNode.Children.Add(new DbViewModel { Name = tableName });
                    }
                }
            }
        }
    }

    private IEnumerable<string> GetNameList(DataRowCollection drc, int index)
    {
        return drc.Cast<DataRow>().Select(r => r.ItemArray[index].ToString()).OrderBy(r => r).ToList();
    }

    private static string GetConnectionString()
    {
        // To avoid storing the connection string in your code,
        // you can retrieve it from a configuration file.
        return @"Data Source=**-PC\SQLSERVER2016;Database=DB_DEMO;" +
           "Integrated Security=true;";
    }

    public ObservableCollection<DbViewModel> Items { get; set; }
}
}

Thanks in advance for your help guys.




Checkboxes are running macro on selected cell row; Need them to run on linked cell row

I have a workbook in which specific line items are to be completed by a staff member and, once completed, they are to be checked off as complete. This triggers the row/range to the left of the checkbox to be selected, copied and pasted into the next worksheet on the first available row. The current row is then cleared from the first worksheet. Each worksheet has the checkboxes pre-filled in and pre-linked to cells. The issue I'm having is that when the checkbox is selected, the runall macro activates on the row that is currently selected instead of the row that the checkbox resides in and is linked to the cell in. So, for example, if the checkbox is in row M2 but the currently selected cell is B8, the macro will try to copy and paste row 8 instead of the intended row 2. As there is no undo with macros this results in a major headache. Any help would be greatly appreciated!

Sub RUNALLOPEN()
Dim response As VbMsgBoxResult
response = MsgBox("Are you sure you wish to clear this row and send to the Lab?", vbYesNo + vbExclamation, "Confirm Error Resolution")
If response = vbNo Then
    Dim cbx As CheckBox
    Set cbx = ActiveSheet.CheckBoxes(Application.Caller)
    With cbx.TopLeftCell.Offset(0, -1)
    cbx.Value = xlOff
    End With
    Exit Sub
End If
If response = vbYes Then
'rest of code
    Call movedataOPEN2LAB
    Call clearcellsOPEN
     End If
End Sub


    Sub movedataOPEN2LAB()
 Dim cbx As CheckBox

        'Application.Caller returns the name of the CheckBox that called this macro
        Set cbx = ActiveSheet.CheckBoxes(Application.Caller)

        '.TopLeftCell returns the cell address located at the top left corner of the cbx checkbox
        With cbx.TopLeftCell.Offset(0, -1)

            'Check the checkbox status (checked or unchecked)
            If cbx.Value = xlOn Then
            ' Checkbox is Checked
     Range(Cells(cbx.TopLeftCell.Offset(0, -1).Row, 1), Cells(cbx.TopLeftCell.Offset(0, -1).Row, 11)).Select
     Selection.Copy
     Sheets("Lab").Select
     Range("A" & Rows.Count).End(xlUp).Offset(1).Select
     ActiveSheet.Paste
     ActiveSheet.Range("H" & Selection.Row).Formula = "=VLOOKUP(INDIRECT(""G"" & ROW()),'Source Data'!$D$1:$J$36,6,FALSE)"
     ActiveSheet.Range("I" & Selection.Row).Value = "Lab"
     Range("A2").Select
  End If
        End With
End Sub


Sub clearcellsOPEN()
 On Error Resume Next
 Worksheets("Open").Activate
 Range(Cells(Selection.Row, 1), Cells(Selection.Row, 15)).Select
 Selection.SpecialCells(xlCellTypeConstants).ClearContents
 Range(Cells(Selection.Row, 1), Cells(Selection.Row, 1)).Select
End Sub




checking a checkbox in recyclerview making other random checkboxes checked too android

I have one recyclerview adapter which has a checkbox.. when i try to check one box recyclerview makes random checkboxes checked too.. Actually i found the error its because all checkboxes have one state and reuses the view.. and also i have many options posted in stackoverflow but nothing worked for me..

This below am checking in the table if there is any item then that particular item checkbox should be checked..

if(Objects.equals(orderTable.getItemCode(), items.getItemCode()) && Objects.equals(orderTable.getStoreId(), storesPojos.getId()))
                {
                 /*   Log.e(TAG+" Order Table Code", String.valueOf(orderTable.getItemCode()));
                    Log.e(TAG+" ItemsPojo Code", String.valueOf(items.getItemCode()));

                    Log.e(TAG +" Order Table ID",orderTable.getStoreId());
                    Log.e(TAG+" store ID",orderTable.getStoreId());*/

                    Log.e("Position of Adapter///", String.valueOf(position));
                    Log.e("SelectedPosition of Adapter///", String.valueOf(selectedPosition));
                    if(selectedPosition == position){
                        holder.checkBox.setChecked(true);
                    }
                    else{
                        holder.checkBox.setChecked(false);
                    }
                    checked++;
                    noOfItems.setText(String.valueOf(checked));
                }

This below code is my checkbox.setOnCheckedChangeListener()

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

                ItemsPojo itemsPojo = itemList.get(position);

                if(selectedPosition == position)
                {
                    checked++;
                    noOfItems.setText(String.valueOf(checked));
         dbHelper.insertItemFromOrderTable(itemsPojo.getItemCode());
                }
                else
                {
                    checked--;
                    noOfItems.setText(String.valueOf(checked));

          dbHelper.deleteItemFromOrderTable(itemsPojo.getItemCode());
                }




How to bind multiple elements in PowerShell WPF

I am new to WPF in PowerShell. I am building a small app to perform on demand SQL backups by selecting databases from a form as shown in this capture. WPF PowerShell Form

I have the form working and able to do backups. I am now trying to disable the backup/restore button so that they are only clickable when at least one of the checkboxes has been checked. That requires the binding of backup button to checkboxes (in my understanding). I have been able to find a way to bind it with one checkbox but cannot find a way to do it for multiple checkboxes. My XAML for checkboxes and button is as below.

<CheckBox Name="UAT_DB1" Content="UAT-DB1" HorizontalAlignment="Left" Margin="21,113,0,0" VerticalAlignment="Top" Cursor=""/>
<CheckBox Name="UAT_DB2" Content="UAT-DB2" HorizontalAlignment="Left" Margin="21,140,0,0" VerticalAlignment="Top"/>
<Button Name="btn_backup" Content="Backup" HorizontalAlignment="Left" Height="29" Margin="238,343,0,0" VerticalAlignment="Top" Width="78" IsEnabled="{Binding ElementName=UAT_DB1, Path=IsChecked}"/>

If I select DB1, the button is enabled and on click, checks what has been selected from all the checkboxes and backs up all those databases. Below is the code for click function on backup button.

$WPFbtn_backup.Add_Click(
{ 
    foreach($var in $vars)
    {
        if($var.Name -match "WPFUAT" -and $var.Value.IsChecked -eq $true)
        {
            $name = $var.Value.Content
            $dbs = $dbs + $name
        }        
    }
    if ($dbs.Length -gt 0)
    {
        $msg = $dbs -join "`n"       
        $confirmation = [System.Windows.MessageBox]::Show("Following DBs will be backed up.`n`n$msg",'Tipper','OKCancel','Info')
    }
    else
    {
        [System.Windows.MessageBox]::Show("`nYou have to select a DB to backup or restore.",'Tipper','OK','Warning')
    }        
    switch($confirmation)
    {
        'OK'{
            Backup-Database($dbs)
        }
        'Cancel'{
            Write-Host "You clicked No"
        }
    }       
}

)

Above code calls in a function to backup the DB. This function is as below.

function Backup-Database ($dbnames) 
{    
    foreach( $db in $dbnames )
    {
        Write-Host "[Now backing up $db]"
        Backup-SqlDatabase -Database $db -BackupFile "S:\backup\$db.bak" -ServerInstance localhost
    }
    [System.Windows.MessageBox]::Show("`nDatabase Backup has completed.",'Tipper','OK','Info')    
}

Thanks for reading and your help.




Values of Spinner, Radio Button and check box duplicating when scrolling in RecyclerView

I have a RecyclerView which have four type of Views

  1. EditText
  2. Radio Button
  3. CheckBox
  4. Spinner

When I Scroll the RecyclerView with Some content filled (like Selecting a Radio Button) then the value is getting duplicated in the next views also, as my views are repeating again.

My Adapter Code is below

ExerciseTestAdapter

    public class ExerciseTestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<String> mList;
    private Context mContext;

    private final int FIRST_TYPE = 0;
    private final int SECOND_TYPE = 1;
    private final int THIRD_TYPE = 2;
    private final int FOURTH_TYPE = 3;

    public ExerciseTestAdapter(Context mContext) {
        mList = new ArrayList<>();
        this.mContext = mContext;    
    }

    public void addAllItems(List<String> items) {
        mList.addAll(items);
        notifyDataSetChanged();
    }

    public void deleteAll() {
        mList.clear();
        notifyDataSetChanged();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        RecyclerView.ViewHolder holder;
        View v;
        Context context = parent.getContext();


        switch (viewType) {
            case FIRST_TYPE:
                v = LayoutInflater.from(context).inflate(R.layout.item_question_text, parent, false);
                holder = new QuestionEditTextViewHolder(v);
                break;

            case SECOND_TYPE:
                v = LayoutInflater.from(context).inflate(R.layout.item_question_spinner, parent, false);
                holder = new QuestionSpinnerViewHolder(v);
                break;

            case THIRD_TYPE:
                v = LayoutInflater.from(context).inflate(R.layout.item_question_radio, parent, false);
                holder = new QuestionRadioViewHolder(v);
                break;

            case FOURTH_TYPE:
                v = LayoutInflater.from(context).inflate(R.layout.item_question_chk_box, parent, false);
                holder = new QuestionCheckBoxViewHolder(v);
                break;

            default:
                holder = null;
                break;
        }

        return holder;
    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        try {
            switch (holder.getItemViewType()) {
                case FIRST_TYPE:
                    QuestionEditTextViewHolder vh1 = (QuestionEditTextViewHolder) holder;
                    vh1.mQuestionNumber.setText(String.valueOf(position));

                    break;

                case SECOND_TYPE:
                    QuestionSpinnerViewHolder vh2 = (QuestionSpinnerViewHolder) holder;
                    vh2.mQuestionNumber.setText(String.valueOf(position));
                    break;

                case THIRD_TYPE:
                    QuestionRadioViewHolder vh3 = (QuestionRadioViewHolder) holder;
                    vh3.mQuestionNumber.setText(String.valueOf(position));

                    break;

                case FOURTH_TYPE:

                    QuestionCheckBoxViewHolder vh4 = (QuestionCheckBoxViewHolder) holder;
                    vh4.mQuestionNumber.setText(String.valueOf(position));

                    break;

                default:

                    break;
            }


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

    public int getItemViewType(int position) {

        int SELECTED_TYPE;

        switch (mList.get(position)) {
            case "1":
                SELECTED_TYPE = FIRST_TYPE;
                break;

            case "2":
                SELECTED_TYPE = SECOND_TYPE;
                break;

            case "3":
                SELECTED_TYPE = THIRD_TYPE;
                break;

            case "4":
                SELECTED_TYPE = FOURTH_TYPE;
                break;

            default:
                SELECTED_TYPE = 100;
                break;

        }
        return SELECTED_TYPE;
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    private class QuestionEditTextViewHolder extends RecyclerView.ViewHolder {
        TextView mQuestionNumber;

        QuestionEditTextViewHolder(View v) {
            super(v);
            mQuestionNumber = v.findViewById(R.id.tv_question_num);
        }
    }

    private class QuestionSpinnerViewHolder extends RecyclerView.ViewHolder implements AdapterView.OnItemSelectedListener {

        private AppCompatSpinner mSpinnerAnswer;
        TextView mQuestionNumber;

        QuestionSpinnerViewHolder(View v) {
            super(v);

            String[] selectClass = {"Select", "YES", "NO", "OPTION 3", "OPTION 4"};
            mQuestionNumber = v.findViewById(R.id.tv_question_num);
            mSpinnerAnswer = v.findViewById(R.id.spinner_answer);

            ArrayAdapter classAdapter = new ArrayAdapter(mContext, android.R.layout.simple_spinner_item, selectClass);
            classAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mSpinnerAnswer.setAdapter(classAdapter);

            mSpinnerAnswer.setOnItemSelectedListener(this);

        }

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    }


    private class QuestionRadioViewHolder extends RecyclerView.ViewHolder {

        TextView mQuestionNumber;

        QuestionRadioViewHolder(View v) {
            super(v);
            mQuestionNumber = v.findViewById(R.id.tv_question_num);
        }
    }


    private class QuestionCheckBoxViewHolder extends RecyclerView.ViewHolder {

        TextView mQuestionNumber;

        QuestionCheckBoxViewHolder(View v) {
            super(v);

            mQuestionNumber = v.findViewById(R.id.tv_question_num);

        }
    }
}

My Activity Code where I am setting my RecycerView

 mExerciseRecycler = (RecyclerView) findViewById(R.id.exercise_recycler_view);

    ExerciseTestAdapter mTopicAdapter = new ExerciseTestAdapter(mContext);
    mExerciseRecycler.setLayoutManager(new LinearLayoutManager(mContext));
    mExerciseRecycler.setAdapter(mTopicAdapter);

    List<String> mLIst = new ArrayList<>();

   //Adding Dummy Data so that there can be many views in Recycler 
    mLIst.add("1");
    mLIst.add("2");
    mLIst.add("3");
    mLIst.add("4");

    mLIst.add("3");
    mLIst.add("4");
    mLIst.add("2");
    mLIst.add("1");

    mLIst.add("4");
    mLIst.add("3");
    mLIst.add("1");
    mLIst.add("2");

    mTopicAdapter.addAllItems(mLIst);

Any help is appreciated. Thanks in Advance




Creating check box dynamically using itext java

i am trying to create check box and tried with the following code using itext

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfFormField;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.RadioCheckField;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class RadioGroupMultiPage1
{

    public static final String DEST = "C:\\CheckBox.pdf";
    /** Possible values of a Choice field. */
    public static final String[] LANGUAGES = {"English", "German", "French", "Spanish", "Dutch"};

    public static void main(String[] args) throws DocumentException, IOException
    {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new RadioGroupMultiPage1().createPdf(DEST);
    }
    public void createPdf(String dest) throws IOException, DocumentException
    {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
        // create a radio field spanning different pages
        PdfFormField radiogroup = PdfFormField.createRadioButton(writer, true);
        radiogroup.setFieldName("language");
        Rectangle rect = new Rectangle(40, 806, 60, 788);
        RadioCheckField radio;
        PdfFormField radiofield;
        for (int page = 0; page < LANGUAGES.length;)
        {
            radio = new RadioCheckField(writer, rect, null, LANGUAGES[page]);
            radio.setBackgroundColor(new GrayColor(0.8f));
            radiofield = radio.getRadioField();
            radiofield.setPlaceInPage(++page);
            radiogroup.addKid(radiofield);
        }
        writer.addAnnotation(radiogroup);
        // add the content
        for (int i = 0; i < LANGUAGES.length; i++)
        {
            cb.beginText();
            cb.setFontAndSize(bf, 18);
            cb.showTextAligned(Element.ALIGN_LEFT, LANGUAGES[i], 70, 790, 0);
            cb.endText();
            document.newPage();
        }
        // step 5
        document.close();
    }
}

but it is creating only text and i dont even get to see the check box or it is not creating.

I am trying to create something like the following image. also it would be great help if some one helps me as how to read the values back if the check box is selected.

enter image description here




jeudi 26 octobre 2017

checkboxes for attendance in visualforce page

I have requirement to display attendance register of a class using visualforce page. I have create a Student__c Object (Name,Roll no) and a Attendance__c Object(Student__c,Date__c,Checkbox__c). Now I want to display a table with Roll number,Student__c and days in a month in header and for each day I need to have check boxes for each student.




JavaFX Custom CheckComboBox

I am using CheckComboBox control from ControlsFX project.

But I want to create a custom rule:

When you click at Item0, then it should clean all other selections. If you click at Item0 again, it remain checked. If you select Item(X), it clean Item0 and select Item(X).

The idea is that Item0 should be the "All" Option.

enter image description here




Thymeleaf - Checked attribute of checkbox is not set in th:each OR how to properly restore a list of checkboxes some of which were previously checked

In my app I want to create a new Risk ( an instance of Risk object ) and when it is created I want to display 5 checkboxes and three radio buttons. Selected options are specific to each instance of Risk object.

Later I want to display a list of all added Risks with an Edit option button on each Risk. I want my app to restore the view specific to a selected Risk ( when an Edit button on a selected risk is clicked ) - with Risk name, all checkboxes and radio-buttons checked as selected previously. And I want to be able to edit these checkbox selections again so that all new changes were properly reflected in MySQL.

As a newbie in Thymeleaf I did the following:

<div th:each="top : ${topic}">
    <input type="checkbox" th:field="*{topic}" th:checked="${top.checked}" th:value="${top.name}"/><label th:text="${top.name}">Something is wrong !</label>
</div>

I am sure that Controller and Hibernate/MySQL part works properly ( I checked using Logs ).

This works just fine - but only if I have selected only one checkbox ( initially when I added a risk ).

If I select more than one checkbox (when adding a risk) and later select this risk for editing no checkboxes are checked.

What is wrong ?




Adding two Onclicks for items in Listview (Checkbox with the addition starting a new activity, both of which are seperate)

I am trying to build a listview that has a checkbox next to each item. In addition, I want some of the items, when I click on them, to go to a new activity (It will take me to a new list with checkboxes). The problem is that if I click on each item, not matter which particular area of item, the box is checked. I need the box to be checked only when I click on the checkbox. In nnother words, I want to be able to check each item only when I click the checkbox, and anywhere else on each item, start a new activity.

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"

<ListView
    android:id="@+id/fruitselector"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true" />

checkboxlayout.xml:

<CheckedTextView xmlns:android="http://ift.tt/nIICcg"
android:id="@+id/checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:padding="20sp"
    />

MainActivity: The Checkbox Works, but the Onclick for a new acvivity does not. (The Main2 and the Main3 Acivity are the new activities).

package com.example.jesse.languageswitcher;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import android.widget.ListView;
import android.widget.TextView;


import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

    ArrayList<String> selectedItems;

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



        selectedItems=new ArrayList<String>();


    }


    public void onStart(){
        super.onStart();
        ListView chl=(ListView) findViewById(R.id.fruitselector);
        chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        String[] items={"Apple","Pear","Peach","watermelon","Orange","Grape"};
        ArrayAdapter<String> aa=new ArrayAdapter<String>(this,R.layout.checkboxlayout,R.id.checkbox,items);
        chl.setAdapter(aa);
        chl.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String selectedItem = ((TextView) view).getText().toString();
                if(selectedItems.contains(selectedItem))
                    selectedItems.remove(selectedItem); 
                else
                    selectedItems.add(selectedItem); 

                if (position == 0) {
                    Intent myintent = new Intent(view.getContext(), Main2Activity.class);
                    startActivityForResult(myintent, 0);
                }
                if (position == 1) {
                    Intent myintent = new Intent(view.getContext(), Main3Activity.class);
                    startActivityForResult(myintent, 1);
                }
            }

            });
    }
        }

Here is my old code, in which the starting a new activity worked. The xml files are the same except there is no checkboxlayout.xml

public class MainActivity extends AppCompatActivity {

    String items[] = new String[]{
"Apple", "Orange", "Pear"
};

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

        Intent myintent = getIntent();
        String value = myintent.getStringExtra("myintent");
        TextView textview = (TextView)findViewById(R.id.textView2);
        textview.setText(value);



        ListView listView = (ListView) findViewById(fruitselector);
        ArrayAdapter<String> adapter =  new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

////This is the code that starts a new activity if I click on certain items.
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position==0){
                Intent myintent = new Intent(view.getContext(), Main2Activity.class);
                startActivityForResult(myintent, 0);
            }
                if (position==1){
                    Intent myintent = new Intent(view.getContext(), Main3Activity.class);
                    startActivityForResult(myintent, 1);
                }

            }
            });
}}




Nested checkboxes not working with more than one main option

I've used the following codepen snippet to implement nested checkboxes into my HTML page. The original code only catered for one set of nested checkboxes so I've tried to expand to multiple. So far my code has 2 problems, that I can see:

  1. The onclick is not binding to each of the checkboxSubOptions
  2. The checkboxSubOptions is being overwritten on each loop so the checkboxMainOption.onclick no longer works for the first checkboxes
$(document).ready(function() {
        
        var expandableCheckboxes = document.getElementsByClassName("expandable-checkbox");
        for (var i = 0; i < expandableCheckboxes.length; i++) {
                
                var checkboxMainOption = expandableCheckboxes[i].getElementsByClassName("expandable-checkbox-main-option")[0];
                
                var checkboxSubOptions = expandableCheckboxes[i].getElementsByClassName("expandable-checkbox-sub-option");
                checkboxSubOptions.onclick = function() {
                        
                        var checkedCount = 0;
                        for (var j = 0; j < checkboxSubOptions.length; j++) {
                                if (checkboxSubOptions[j].checked) {
                                        checkedCount++;
                                }
                        }
                        
                        checkboxMainOption.checked = checkedCount > 0;
                        checkboxMainOption.indeterminate = checkedCount > 0 && checkedCount < checkboxSubOptions.length;
                }
                
                checkboxMainOption.onclick = function() {
                        
                        for (var j = 0; j < checkboxSubOptions.length; j++) {
                                checkboxSubOptions[j].checked = checkboxMainOption.checked;
                        }
                }
        }
});
body {
  color: #555;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

ul {
  list-style: none;
}

li {
  margin-top: 1em;
}

label {
  font-weight: bold;
}
<html>
  <head>
        <script src="http://ift.tt/2a1Bldc"></script>
  </head>
  <body>
    <div class="checkbox-container">
      <ul>
        <li>
                  <div class="expandable-checkbox">
            <label><input type="checkbox" class="expandable-checkbox-main-option">Main 1</label>
            <ul>
              <li><label><input type="checkbox" class="expandable-checkbox-sub-option">Main 1 Sub 1</label></li>
              <li><label><input type="checkbox" class="expandable-checkbox-sub-option">Main 1 Sub 2</label></li>
              <li><label><input type="checkbox" class="expandable-checkbox-sub-option">Main 1 Sub 3</label></li>
            </ul>
                  </div>
        </li>
        <li>
                  <div class="expandable-checkbox">
            <label><input type="checkbox" class="expandable-checkbox-main-option">Main 2</label>
            <ul>
              <li><label><input type="checkbox" class="expandable-checkbox-sub-option">Main 2 Sub 1</label></li>
              <li><label><input type="checkbox" class="expandable-checkbox-sub-option">Main 2 Sub 2</label></li>
              <li><label><input type="checkbox" class="expandable-checkbox-sub-option">Main 2 Sub 3</label></li>
            </ul>
                  </div>
        </li>
      </ul>
    </div>
          
  </body>
</html>



RShiny : checkBox format

Current status of the boxes : enter image description here

I am unable to improve the following things :

  1. Have the text in a row by itself(The Select the modules... one)
  2. The box and text are not aligned on the same line.
  3. The checkboxes on the top line are slightly truncated.(the remaining is encircled below)
  4. The labels(a to j) need to be in white bold text.

This is what I have tried so far :

code for checkBox :

controls <-
  list(tags$div(align = 'left', 
                class = 'multicol', 
                checkboxGroupInput(inputId  = 'modules', 
                                   label    = my_div("Step 1 : Select the modules to be executed", strong_em = "strong", 22, "left"), 
                                   choices  = c(process_names),
                                   selected = "",
                                   inline   = FALSE)))

code to get multicolumn, larger boxes etc

tags$style(type='text/css', 
          "label {font-size: 22px; }  #controls the text of check-boxes
           input[type=checkbox] {transform: scale(2);}#controls the size of checkbox
           .multicol {font-size:22px; height: 150px; 
                      -webkit-column-count: 4; 
                      -moz-column-count: 4; 
                      column-count: 4; -moz-column-fill: auto;
                     -column-fill: auto;} #increases the size of checkboxes
           div.checkbox {margin-top: 10px;color:'#FFFFFF';font-weight: bold;}
  ")

the main layout of code :

shinyUI(fluidPage(
  # here the tags$style appear,

  sidebarLayout(
    position = "left",
    sidebarPanel(controls)
    mainPanel()
))