jeudi 31 janvier 2019

ASP.net web application with Angular - how to

probably this question has been asked by many people, but I find it so difficult to understand how both can be made to work together.

I am currently working on a web application, I have got a web form with some .net controls. I have programmed a web form to load a gridview pragmatically from code behind, there is a specific column in the gridview that contains a textbox control. Now, I want to do something like, when user hover's a mouse on the textbox, a popup window should open contains checkboxes that pulls data from a database ( of course the checkbox containing the value from the textbox should be auto selected ). I know this is possible, but I want to learn angular and I want to implement it using angular, but I am lost.

Are there any tutorials that I can learn from, also, what does Angular CLI do, node.js ( must I use this, since I will running it from the IIS server ), why are the folder hierarchies for angular so confusing.




d3 order of label and checkbox chained

My question is complimentary for this post, but since I do not have enough reputation, I could not ask it in a comment!

I was trying to create checkboxes and labels dynamically using d3. Getting it to work with label + checkbox is easy. What I wanted to do was to put the checkbox before label by replicating this HTML code:

<label><input type="checkbox" id="checkbox1">Option 1</label>

The solution in the aforementioned post works, but I don't understand why the chained(nested selection/append) version is not working? (i.e. the code below)

var temp = item.append("label");

temp.append("input")
    .attr("type", "checkbox")
    .attr("checked", true)
    .attr("id", function (d,i) {
        return "checkbox" + i;
    })
    .on("click", function (d,i) {
        ....
    });
temp.text(function (d) {
        return d.text;
    });

I expect the code to add the label's text after input but it does not do so. Can someone please explain why? Am I missing something?




Why boxes are invisible in checkbox?

after created this style:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/offer_text_background</item>
    <item name="colorPrimaryDark">@color/app_background</item>
    <item name="android:checkboxStyle">@style/settingsNotificationCategory</item>
</style>

<style name="settingsNotificationCategory">
    <item name="android:textSize">30sp</item>
</style>

My box from checkbox is removing:

Without this style:

I need create chceckbox dynamically in kotlin:

var checkBox = CheckBox(this)
checkBox.text = category
checkBox.setTextColor(resources.getColor(R.color.customText))
        checkBox.isChecked = true
notificationCategoryLayout.addView(checkBox)

what's happened?

I tried :

var checkBox = CheckBox(this, null, R.style.settingsNotificationCategory)
checkBox.text = category
checkBox.setTextColor(resources.getColor(R.color.customText))
        checkBox.isChecked = true
notificationCategoryLayout.addView(checkBox) 

but the effect is the same...

Thanks for help




mercredi 30 janvier 2019

How to set checkbox ng-checked from server data using AngularJS and save the checked/unchecked back to server data?

This should be a very common problem, invoking an ng-model to parse the data into form (DOM) after which the modified checkbox's ng-checked will be translated back to data values so to be saved back on the server.

I have two check boxes respectively

<table><tbody>
        <tr>
            <td align="left">To be ignored</td><td align="left">Yes 
                <input type="checkbox" ng-model="nm_ignore" /></td>
            <td></td>
        </tr>
        <tr>
            <td align="left">To be excluded</td><td align="left">Yes 
                <input type="checkbox" ng-model="nm_exclude" /></td>
            <td></td>
        </tr>
    </tbody>
</table>

And, my data is

$scope.nm_to_ignore = _a_record._ab_ignore; // "T"
$scope.nm_to_exclude = _a_record._ab_x_style; // "F"

My objective is :
I want a straight-forward easy way (easy-to-maintain codewise, which is, angularJS ng-model) to set the checkboxes CHECKED/UNCHECKED by the data read from the server. Also, I want to be able to save the values represented by CHECKED/UNCHECKED to the data just as it came.




Checkbox on mousedown, uncheck on mouseup

I am making jQuery application where there is a checkbox that is checked only when the mouse/key/touch is pressed. Check on mousedown, uncheck on mouseup.

Even if I use event.preventDefault(), the checkbox remains checked if the mouse button is not down, but the spacebar works fine.

$(function() {
  var cb = $("input");
  cb
    .on("mousedown keydown", function(event) {
      event.preventDefault();
      cb.prop("checked", true);
    })
    .on("mouseup keyup", function(event) {
      event.preventDefault();
      cb.prop("checked", false);
    });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type=checkbox autofocus>

I know the code above needs a bit of work to work correctly in any situation (touch, etc.) but it is written for testing purposes only




Angular | Programmatically set elements attribute

I'm utilizing Angular Material to create an awesome web application. Please consider the following code:

<mat-checkbox class="master" (click)='checkAll()'>Checkbox MASTER</mat-checkbox>
<mat-checkbox class="checkbox">Checkbox 2</mat-checkbox>
<mat-checkbox class="checkbox">Checkbox 3</mat-checkbox>

The code produces three checkboxes. When the first checkbox is checked, the two others should be checked as well. If the first checkbox is not checked, the two others should function normally.

In component:

checkAll() {
  // How can I programmatically set the [checked] property here for .checkbox?
}




How to find controls inside a class with specific class name

Hello all I have a table as follows

function checkAll2(rowClass, status) {
  var dynamicClass = $('.' + rowClass);
  // alert($('.1').find(":checkbox").length);
  alert($('input:checkbox.1').length);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="table1">
  <tr>
    <td>1a:</td>
    <td><input type="checkbox" name="selected" value="1a" class="1"></td>
  </tr>
  <tr>
    <td>1b:
    </td>
    <td><input type="checkbox" name="selected" value="1b" class="1"></td>
  </tr>
</table>

Select All/None above<input type="checkbox" onclick="checkAll2(1,this.checked)" />

But what I need is I would like to reuse this for different classes too so I will pass rowClass so that my input:checkbox should be appended with rowClass and give me the count or the list of controls with that class




How to show/hide a select dropdown with options on check/uncheck checkbox in angular 2

I have the below HTML code in which i have added change event for checkbox, on check of checkbox, the select dropdown should be shown, and on uncheck of checkbox, the select drop down should be hidden. I have added ngIf condition and set the value of showDropDown to true or false in ts file. But i dont know what is wrong, the show/ hide of select dropdown doesnt work. however, if i replace select drop down with a plain text , the show / hide works fine. is there a specific way to achieve show/hide for select drop down?

<div>
            <label>
              <input name="test" type="checkbox" (change)="showHideDropDown($event)">
            </label>
            <label>I receive other income annually</label>
          </div>


              <div *ngIf="showDropDown">
                <select id="form2" class="mdb-select">
                  <option value="" disabled selected>Other Income Amount</option>
                  <option value="1">SAR 2000 and below</option>
                  <option value="2">SAR 2000 to 5000</option>
                  <option value="3">SAR 5000 to 10000</option>
                  <option value="4">SAR 10000 to 20000</option>
                  <option value="5">SAR 20000 to 40000</option>
                  <option value="6">SAR 40000 to 60000</option>
                  <option value="7">SAR 60000 and above</option>
                </select>
              </div>




How to get multiple checked checkbox values?

I want to get the multiple checked checkbox values

Here is my code:

<?php
      foreach ($dosage_form_list as $val) {
?>  

    <input type="checkbox" name="dosage_form_input[]" value="<?php echo $val['dosage_form']?>" <?php echo ($dosage_form_list_exist == $val['dosage_form'] ? 'checked' : ''); ?>>

    <?php echo $val['dosage_form'];?>

<?php

      }

?> 

Here $dosage_form_list_exist is get the multiple checkbox values. But My code shows only one item is checked. I want to show multiple checked values.

In Image-1. I get only one values to checked. And it's ok.

Image-1

But In Image-2. I get multiple values See Like Injection, Suspension, Tablet. But There are no checked checkboxes. Image-2

So That reason I want to get the multiple checked checkbox values.

Can anyone please help me for check this?




How to improve performance of primeNg table that contain checkboxes

I am having some performance issue when using p-table with p-checkbox in it. Table have something around 1000 rows and 15 columns, where 10 of that contain only checkboxes.

So at the end table contain 10000 checkboxes. When I remove checkboxes from the table the time that table needs to generate equals around 5s. When checkboxes are visible time increases to something around 20s!

This table contains only 1000 rows, of course there is sorting, filtering included, but as I wrote before , when I remove checkboxes time of generating the table equals around 5s.

So where is the problem? Even when I left completely empty checkbox declaration , like that:

        <p-checkbox binary="true">
        </p-checkbox>

time is still very big. Here is the structure of my table:

<p-table
  [value]="data">
  <ng-template pTemplate="caption">
  </ng-template>

  <ng-template pTemplate="header">
    <tr>
      <th class="toggle-column"></th>
      <!-- LAST NAME COLUMN -->
      <th class="lastname-column" [pSortableColumn]="'lastName'">
      </th>
  </ng-template>

  // BODY DEFINITION - CHECKBOXES
  <ng-template pTemplate="body" let-row let-expanded="expanded" 
   let-rowIndex="rowIndex">
    <tr>
      <td class="toggle-column"></td>
      <td *ngFor="let col of columns" class="">
        <span class="ui-column-title"></span>
        <p-checkbox
          binary="true"
          [disabled]="!isEditable"
          [(ngModel)]="row[col.field]"
          (onChange)="toggle($event, col.field, rowIndex)">
        </p-checkbox>
      </td>
    </tr>
  </ng-template>

  <ng-template let-row pTemplate="rowexpansion">
    <tr>
      <td>
        <table class="expanded-table">
          <tr *ngFor="let user of row.userGroup.members" class="expanded-row">
            ...
          </tr>
        </table>
      </td>
    </tr>
  </ng-template>

  <ng-template pTemplate="emptymessage">
    <tr>
      <td [attr.colspan]="tableConfig.colspan">
        ui.noRecordsFound
      </td>
    </tr>
  </ng-template>
</p-table>


Pagination and lazy loading on scroll are out of the question - my client does not want this. He wants to see the hole table at once.

I also thought about using ChangeDetectionStrategy.OnPush but each time new checkbox is added the ngOnChanges and ngDoCheck (I divided body template into 3 components to test this hole change detection stuff - in example you see above everything is in one component).

I can I guess use native checkbox, I have already checked that, and time is also very nice around 8s. But I am using primeNg framework for a reason, right ?!

Main problem is with p-checkbox component, it works very slow, and I know the problem is not with rendering, because I checked profiler - there is a massive time needed for something that is going on 'behind the hood' - problem is with change detection I think, not with the rendering itself for sure.

So do you have any idea how I can improve my table ?




How to add custom tax value if a custom checkbox field is checked?

I am trying to add custom tax value at woocommerce checkout page, but I want to show it only for specific country (Italy) and only if a custom checkbox field in the checkout page is checked.

I've already found this answer and I'm trying to adjust to my problem by editing the function conditional_custom_shipping_cost.

I do the following:

// Add a Custom checkbox field for shipping options (just for testing)
add_action( 'woocommerce_after_checkout_billing_form', 'custom_billing_checkbox_for_testing', 10, 1 );
function custom_billing_checkbox_for_testing( $checkout ) {
    $field_id = 'billing_ups_yn';

    // Get the checked state if exist
    $billing_ups = WC()->session->get('billing_ups' );
    if(empty($billing_ups))
        $billing_ups = $checkout->get_value( $field_id );

    // Add the custom checkout field (checkbox)
    woocommerce_form_field( $field_id, array(
        'type' => 'checkbox',
        'class' => array( 'form-row-wide' ),
        'label' => __('Billing UPS'),
    ), $billing_ups );
}

// function that gets the Ajax data
add_action( 'wp_ajax_woo_get_ajax_data', 'woo_get_ajax_data' );
add_action( 'wp_ajax_nopriv_woo_get_ajax_data', 'woo_get_ajax_data' );
function woo_get_ajax_data() {
    if ( $_POST['billing_ups'] == '1' ){
        WC()->session->set('billing_ups', '1' );
    } else {
        WC()->session->set('billing_ups', '0' );
    }
    echo json_encode( WC()->session->get('billing_ups' ) );
    die(); // Alway at the end (to avoid server error 500)
}

// Conditionally changing the shipping methods costs
add_filter( 'woocommerce_package_rates','conditional_custom_shipping_cost', 90, 2 );
function conditional_custom_shipping_cost( $rates, $cart ) {

    if ( WC()->session->get('billing_ups' ) == '1' ){
        if ( 'IT' != WC()->customer->get_shipping_country() ) return;

        $percent = 10;
        # $taxes = array_sum( $cart->taxes ); // <=== This is not used in your function

        // Calculation
        $surcharge = ( $cart->cart_contents_total + $cart->shipping_total ) * $percent / 100;

        // Add the fee (tax third argument disabled: false)
        $cart->add_fee( __( 'TAX', 'woocommerce')." ($percent%)", $surcharge, false );

    }
    return $rates;
}


// The Jquery script
add_action( 'wp_footer', 'custom_checkout_script' );
function custom_checkout_script() {
    ?>
    <script type="text/javascript">
        jQuery( function($){

            // update cart on delivery location checkbox option
            $('#billing_ups_yn_field input').change( function () {
                var checked = 0;
                if ( $('#billing_ups_yn').is(':checked') )
                    checked = 1;

                $.ajax({
                    type: 'POST',
                    url: wc_checkout_params.ajax_url,
                    data: {
                        'action': 'woo_get_ajax_data',
                        'billing_ups': checked,
                    },
                    success: function (result) {
                        $('body').trigger('update_checkout');
                        console.log('response: '+result); // just for testing
                    },
                    error: function(error){
                        console.log(error); // just for testing
                    }
                });
            });
        });
    </script>
    <?php
}

but I don't get the desired behavior (to work only if Italy selected)




mardi 29 janvier 2019

Multiple checkbox in react native

How do I make a multiple checkbox in the react native <CheckBox></CheckBox>?

Currently my checkbox is like this :

if(this.state.specialise_list != null){
  return this.state.specialise_list.map((data, i)=>(
    <View key={i} style=>
      <CheckBox
        containerStyle=
        value={this.state.specialise}
        onValueChange={(itemValue, itemKey) => this.setState({ specialise: itemValue })} />
      <Text style=> { data.name }</Text>
    </View>
  ))
}

My above code will check all the checkbox. I'm trying to insert the checked checkbox in an array in this form selected_specialise: [ '1', '2', '5', '24' ]; where the data will be removed from the array if the specific checkbox is unchecked.




How to get multiple checked checkbox values in codeigniter update from?

I want to get the multiple checked checkbox values

Here is my code:

<?php
      foreach ($dosage_form_list as $val) {
?>  

    <input type="checkbox" name="dosage_form_input[]" value="<?php echo $val['dosage_form']?>" <?php echo ($dosage_form_list_exist == $val['dosage_form'] ? 'checked' : ''); ?>>

    <?php echo $val['dosage_form'];?>

<?php

      }

?> 

Here $dosage_form_list_exist is get the multiple checkbox values. But My code shows only one item is checked. I want to show multiple checked values.

In Image-1. I get only one values to checked. And it's ok.

Image-1

But In Image-2. I get multiple values See Like Injection, Suspension, Tablet. But There are no checked checkboxes. Image-2

So That reason I want to get the multiple checked checkbox values.

Can anyone please help me for check this?




Error: mat-form-field, mat-selection-list must contain a MatFormFieldControl

I am trying to add a checkbox and attach to a formfield. I am using angular 7. I am using tags mat-form-field, and for this I am getting error "ERROR Error: mat-form-field must contain a MatFormFieldControl."

I have checked my Component code and made sure FormControl exist. Though it is not very clear but add formControl "mat-selection-list"

//DECLARE CONTROL
    preexistingControl = new FormControl('',[Validators.required]);
// CHECKBOX DATA
    preExistingCondList: PreExistingCond[] = [
            {id:'0' ,value:'None'},
            {id:'1' ,value:'Arthritis'}, 
            {id:'2' ,value:'Asthma'},];
//ADD TO FormGroup
    preexistingControl:this.preexistingControl,

HTML CODE

<mat-form-field>
            <mat-selection-list #preConditions placeholder="PreExisting Conditions" [formControl]="preexistingControl">
                <mat-list-option *ngFor="let preExistingCond of preExistingCondList">
                                
                </mat-list-option>
            </mat-selection-list>
        </mat-form-field>


It is throwing following error:

ERROR Error: mat-form-field must contain a MatFormFieldControl.
    at getMatFormFieldMissingControlError (form-field.es5.js:119)
    at MatFormField.push../node_modules/@angular/material/esm5/form-field.es5.js.MatFormField._validateControlChild (form-field.es5.js:764)
    at MatFormField.push../node_modules/@angular/material/esm5/form-field.es5.js.MatFormField.ngAfterContentInit (form-field.es5.js:453)
    at callProviderLifecycles (core.js:22311)
    at callElementProvidersLifecycles (core.js:22292)
    at callLifecycleHooksChildrenFirst (core.js:22282)
    at checkAndUpdateView (core.js:23213)
    at callViewAction (core.js:23450)
    at execComponentViewsAction (core.js:23392)
    at checkAndUpdateView (core.js:23215)

I have check the formControl exist and the ref id is correct. Anyone facing this issue please provide an answer.




Custom CSS checkbox and aligning tick on multiple lines

I've created a custom checkbox using :before and :after pseudo-elements on a <span>, which works great on single lines, but the tick hovers above the box when there's more than one line of text in its <span>.

I've tried using relative values for positioning, but nothing has worked.

<ul class="calendar-filter-menu-cont">
  <li>
    <label>
      <input type="checkbox">
      <span>One line</span>
    </label>
  </li>

  <li>
    <label>
      <input type="checkbox">
      <span>This is the second item in the list</span>
    </label>
  </li>

  <li>
    <label>
      <input type="checkbox">
      <span>This is the third item in the list</span>
    </label>
  </li>
</ul>


ul.calendar-filter-menu-cont {
  color: black;
  column-count: 3;
  max-width: 500px;
}
ul.calendar-filter-menu-cont > li {
  break-inside: avoid-column;
}
ul.calendar-filter-menu-cont > li label {
  display: flex;
  position: relative;
}
ul.calendar-filter-menu-cont > li label:not(:last-child) {
  margin-bottom: 10px;
}
ul.calendar-filter-menu-cont > li label input[type="checkbox"] {
  margin-right: 1em;
  opacity: 0;
}
ul.calendar-filter-menu-cont > li label input[type="checkbox"] + span:before {
  content: '';
  display: inline-block;
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
  border: 1px solid #979797;
  width: .8em;
  height: .8em;
  background-color: #f3f3f3;
  box-shadow: inset 0 0 5px 0 rgba(0, 0, 0, 0.2);
}
ul.calendar-filter-menu-cont > li label input[type="checkbox"]:checked + span:after {
  content: '';
  position: absolute;
  top: .7ex;
  left: .35ex;
  width: .9ex;
  height: .45ex;
  background: rgba(0, 0, 0, 0);
  border: 3px solid blue;
  border-top: none;
  border-right: none;
  transform: rotate(-45deg);
}

Demo: https://codepen.io/anon/pen/PVGxBz




How to set selected properties in multiple checkboxes with foreach loop in PHP?

I want to display all the category and I want to set selected properties to multiple Checkboxes.

<div class="col-md-10">
<?php 
$allCategories = $category->getAllCategory();
if ($allCategories) {
    foreach ($allCategories as $items) {

        $categoryAccess = $category_permitted->getCategoriesByUserId($user_info[0]->id);

        ?>
        <input type="checkbox" name="cat_access[]" value="<?php echo $items->id ?>"<?php echo (isset($categoryAccess) && $categoryAccess->id == $items->id) ? 'selected' : '' ?>><?php echo $items->title?>
        <?php
    }
}
 ?>

I have 5 categories which have checkboxes and for the output, 3 of the categories should be checked. I am getting error in <?php echo (isset($categoryAccess) && $categoryAccess->id == $items->id) ? 'selected' : '' ?> it gives this error: Trying to get property 'id' of non-object and when I do <?php echo (isset($categoryAccess) && $categoryAccess[0]->id == $items->id) ? 'selected' : '' ?> it gives data but of 0 index only.




How do I set the value of multiple checkboxes that is linked to an associated table because of many-to-many relationship MVC

I have a checkbox where the user can choose a number of services that can be provided to a company. I can save the services and that all works fine. The services are linked to a company through a CompanyService table which as the companyId and the serviceId.

If the user clicks on an edit button I am unsure how to have the boxes checked on load. I've had a look at other options using IsChecked however I cannot add a property to my services model as it serves multiple companies. How would I go about doing it?

My Service Model

    public int Id { get; set; }
    [Required]
    public string Name { get; set; }

    public virtual ICollection<CompanyService> CompanyServices { get; set; }
    public virtual ICollection<TrustService> TrustServices { get; set; }

My CompanyService model

    [Key]
    [Column(Order =1)]
    public int CompanyId { get; set; }
    [Key]
    [Column(Order =2)]
    public int ServiceId { get; set; }

    public virtual Company Company { get; set; }
    public virtual Service Service { get; set; }

And finally the Razor code

<div class="col-lg-5">
                <div class="col-12">
                    <ul class="list-group" id="serviceList">
                        <li class="list-group-item service-heading">Services</li>
                        @foreach (var service in Model.Services)
                        {
                            <li class="list-group-item">
                                <input type="checkbox" name="services" value="@service.Id" id="check_@service.Id" />
                                <label for="check_@service.Id">@service.Name</label>
                            </li>
                        }
                    </ul>
                </div>
            </div>

Do I need to create a IsChecked on my CompanyServices table and try and assign the checked value from there? If so how would I do that?




how to get the selected checkbox row value in a gridview using javascript by dynamic created checkbox

i am created dynamic checkbox control in grid view but for multiple row it add with same id fro checkbox how i can get row value of selected checkbox

here is my dyanamic control at gridvie rowdatabound event

 protected void grdreport_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        int temp = e.Row.Cells.Count;

        temp--;






        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            if (temp >= 3)
            {



                strheadertext1 = grdreport.HeaderRow.Cells[3].Text;

                CheckBox cb1 = new CheckBox();
                cb1.ID = "cb1";
                cb1.Text = e.Row.Cells[3].Text;



                e.Row.Cells[3].Controls.Add(cb1);



            }
}

and i am getting value on button click

protected void BtnSave_Click(object sender, EventArgs e)
    {






        foreach (GridViewRow row in grdreport.Rows)
        {


            CheckBox checkbox1 = (CheckBox)row.FindControl("cb1");
            checkbox1.Checked = true;
            if (checkbox1.Checked)
            {
                string itemname = row.Cells[0].Text;
                string particular = row.Cells[1].Text;
                string qty = row.Cells[2].Text;
            }

        }



    }

but when i am getting value it gives me first row value whenever i check second row checkbox




lundi 28 janvier 2019

how to migrate

Hi i have these multiboxes in my JSP

<html:multibox property="selectedPDFSignatures" value="PDF_SIG" name="manageVPForm" onclick="setPdfChildSignatures(this)"/>
<html:multibox property="selectedPDFSignatures" value="PDF_SIG_TS" name="manageVPForm" onclick="setPdfChildSignatures(this)"/>
<html:multibox property="selectedPDFSignatures" value="PDF_SIG_TS_RI" name="manageVPForm" onclick="setPdfChildSignatures(this)"/>
<html:multibox property="selectedPDFSignatures" value="PDF_SIG_TS" name="manageVPForm" onclick="setPdfChildSignatures(this)"/>
<html:multibox property="selectedPDFSignatures" value="PDF_SIG_TS_RI" name="manageVPForm" onclick="setPdfChildSignatures(this)"/>

i have done something like this for first checkbox

<s:iterator var="row" value="%{manageVPForm.selectedPDFSignatures}">
<input type="checkbox" name="manageVPForm.checked" value="${row.PDF_SIG}" <s:property value="%{manageVPForm.checked.contains(#row.PDF_SIG)?'checked='checked'':''}"/>/>    
</s:iterator>

but it does not solved my problem, can you please tell me how to migrate all above checkboxes ? i have also seen this question on stackoverflow but it is not working for me Question




Cannot save multiple checkbox value checked after a form submits on ajax load in php

I have one simple form which has: From date, To date When i click on submit i get list of car bookings on ajax load. In each row there is a checkbox to select that row and after multiple selection of row a common button is clicked to add bill on next page. Now my problem is I want to select multiple rows and again fill from date, to date and then submit form to get other list to again select other rows to add bill, now the problem is when I again submit form the old selected rows does not get saved so that i can get all rows selected all together on bill page. 1. This is ajax script

<script> $("#button").click(function(){
document.getElementById("loading").style.display = "block"; 
document.getElementById("overlay").style.opacity = '0.2';
var toDate = $("#datepicker2").val();
var fromDate = $("#datepicker").val();  
// var comp = $("#comp").val();
var dataString = 'fromDate='+ fromDate + '&toDate='+ toDate;
$.ajax({
  url: 'CloseBookingload.php',
  data:dataString,
  type: 'POST',
  success: function(result){
          // console.log(result);
           $("#load").show();
          $("#resultData").html(result);
           document.getElementById("loading").style.display = "none"; 
           document.getElementById("overlay").style.opacity = '1';
        }
      }); });</script>

This is my ajax page checkbox field after loads

 <input type="checkbox" id="checkselect" name="checkselect[]" value="<?php echo $row['car_booking_id'];?>">

First Page IMAGE Main Page IMAGE




Remove checkbox in datatable [on hold]

Is there a way to remove checkbox in Flutter DataTable ?

enter image description here




How do you get what an user selected in a checkbox form and then update a mysql database with the information?

I would like to know if this is possible in Javascript, specifically for someone. I have my way of doing it in PHP but I'm not an expert into Javscript.




overflowing RenderFlex flutter

I am trying to make a seemingly easy page with flutter.

It contains of totally five rows where row 1 & 2, 3 & 4 belongs together, and the last row is its own.

Row 1: Centered text Row 2: 8 icon buttons

Row 3: Centered text Row 4: 5 checkboxes

Row 5: Text with a following icon button

The problem I get is the size: I/flutter (22610):◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢ A RenderFlex overflowed by 248 pixels on the right.

I have tried to make the code in different classes, according to their belonging, but then I get this error. When I tried to put the code in containers, the iconButtons and checkBoxes quit working. I have read a lot of questions about similar problems here on Stackoverflow and googled around about it, but I'm still stuck.

class MyIcon extends StatefulWidget {
  @override
  _MyIconState createState() => _MyIconState();
}

class _MyIconState extends State<MyIcon> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.red,
      //   body: Container(
      //     height: 180.0,
      //   color: Colors.lightBlueAccent,

  body: Column(
    mainAxisSize: MainAxisSize.min,
    children: <Widget>[
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(top: 50.0),
          ),
          Text(
            'FIRST TEXT',
            textDirection: TextDirection.ltr,
            style: TextStyle(
              fontSize: 25.0,
              color: Colors.white,
            ),
          ),
        ],
      ),
      Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,

        children: <Widget>[

     //         Padding(padding: EdgeInsets.only(left: 3.0, right: 10.0)),
              _IconButtons(
                headImageAssetPath: 'assets/ico.png',
                onPressed: () {},
              ),
              _IconButtons(
            headImageAssetPath: 'assets/ico.png',
            onPressed: () {},
          ),
          _IconButtons(
            headImageAssetPath: 'assets/ico.png',
            onPressed: () {},
          ),
          _IconButtons(
            headImageAssetPath: 'assets/ico.png',
            onPressed: () {},
          ),
          _IconButtons(
            headImageAssetPath: 'assets/ico.png',
            onPressed: () {},
          ),
          _IconButtons(
            headImageAssetPath: 'assets/ico.png',
            onPressed: () {},
          ),
          _IconButtons(
            headImageAssetPath: 'assets/ico.png',
            onPressed: () {},
          ),
          _IconButtons(
            headImageAssetPath: 'assets/ico.png',
            onPressed: () {},
          ),
        ],
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            "SECOND TEXT'",
            style: TextStyle(fontSize: 25.0, color: Colors.white),
          ),
        ],
      ),
      MyCheckBox(),
    ],
  ),
  //     ),
);
  }
}

class _IconButtons extends StatelessWidget {
  final iconSize = 60.0;
  final String headImageAssetPath;
  final onPressed;

  _IconButtons({this.headImageAssetPath, this.onPressed});

  @override
  Widget build(BuildContext context) {
    return IconButton(
        iconSize: iconSize,
        icon: Image.asset(headImageAssetPath),
        onPressed: () {});
  }
}

class MyCheckBox extends StatefulWidget {
  @override
  _MyCheckBoxState createState() => _MyCheckBoxState();
}

class _MyCheckBoxState extends State<MyCheckBox> {
  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Column(
        children: <Widget>[
          Expanded(
            child: Row(
              children: <Widget>[
                Text(
                  "ANOTHER TEXT",
                  textDirection: TextDirection.ltr,
                  style: TextStyle(
                    fontSize: 25.0,
                    color: Colors.blueGrey,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

This is one of many tries. If you want I can send the code for the checkboxes too. (I'm new to flutter so I'm sorry if my code is bad).

Any help is appreciated. Thank you.




How to change the export value of an existing PDF checkbox with iTextSharp

I've found a good example which shows how to set the checkbox export value (among other properties) for a new checkbox here (see the "CreateCheckBoxList" example):

https://simpledotnetsolutions.wordpress.com/2012/11/01/itextsharp-creating-form-fields/

However I need to change the export value for an existing checkbox. I tried modifying the above example in several different ways but nothing worked.

Just to clarify, the image below shows the checkbox property which I wish to change programmatically using iText:

enter image description here




Is there a way to save the checked/ticked items into an array?

I have done a grid like this using the Checkbox plugin on the images, enter image description here

The data-items have been flagged description, checked/not-checked booleans, id's etc.

export const DATAITEMS: Array<DataItem> = [
{    id: 5451545, 
     name: "Chefs Collection",
     description: "This is item description.",
     image: "~/images/chefscollection.jpg",
     selected: false 
},
];

This is my template code:

<StackLayout class="topbuttons">
<GridLayout columns="*,*" horizontalAlignment="left" verticalAlignment="top">
    <Button class="btn btn-primary topbutton" text="Next" col="1" (tap)="onTap()"></Button>
</GridLayout>

more

<GridLayout tkExampleTitle tkToggleNavButton  class="topgrid" loaded="loaded" >
<RadListView [items]="dataItems" >
    <ng-template tkListItemTemplate let-item="item">
            <GridLayout class="garmentpick">
                <Image [src]="item.image" (tap)="toggleCheck()" class="imageP" >
                 </Image>
                <CheckBox #CB1 checked="false" text="" ></CheckBox>
        </GridLayout>
    </ng-template>
    <ListViewGridLayout tkListViewLayout ios:itemHeight="200" spanCount="2"></ListViewGridLayout>
</RadListView>

typescript

export class Component implements OnInit {
@ViewChild("CB1") firstCheckBox: ElementRef;

toggleCheck() {
    console.log();
    this.firstCheckBox.nativeElement.toggle();
}
onTap() {
    const checkboxArray = new ObservableArray(this.items);
    this._dataItems.forEach((item) => {
       checkboxArray.push(this.firstCheckBox.nativeElement.text);
    });        
}
}

I want to save the clicked items into an array. I created an array, I am pushing the clicked items to the array in the ontap of a submit button, but using Array.push(item.id) only pushes just one item, or repeats it in that array. is there a way I can do this, I'm thinking about data-forms




Angular, button validation work in the wrong order

i have one checkbox in angular 7

when I refresh my page, the good value is here

but when I click the checkbox, the value is the wrong one

there is my code in my html :

<input type="checkbox" [(ngModel)]=material.validated (click)="updateValidation(material)">

in my ts :

public updateValidation(material: any) {
    this.requestService.updateVersionQuotation(this.quotationId, this.versionId, this.quotation);
}




Is there a way to tweak 'Select Multiple' so that it shows '1 selected' or '2 selected' instead of the values?

I am using Select2 in my application and I have run into a problem.

I need a typeahead select box which supports multiple selections with checkboxes and on selecting, shows " selected."

The problem is, there's existence of a dropdown list which supports this BUT it is not typeahead in nature AND there's a typeahead select box supporting this BUT it shows the selected values instead of '1 selected', '2 selected', etc.

Please refer to https://jsfiddle.net/wasikuss/7ak9skbb/ to understand my problem better. I need a combination of the 2nd and 3rd select boxes.

$('.select2-multiple2').select2MultiCheckboxes({
templateSelection: function(selected, total) {
  return "Selected " + selected.length + " of " + total;
}
})

$('.select2-original').select2({
  placeholder: "Choose elements",
  width: "100%"
})

Hope I am clear enough.




dimanche 27 janvier 2019

displaying checkboxes in multiple cols in Angular 6 reactive form

Bootstrap to display dynamic checkboxes in 3 columns

I am following this example to create a list of dynamic checkboxes across 3 columns, currently trying to make it work using static data but later will get from service. Right now, it is not throwing any error but not displaying checkboxes. I am not sure what is incorrect.

Template:

<form [formGroup]="ReportsForm" (ngSubmit)="submit()">

    <div class="col-xs-8">
        <div class="row">
            <div class="col-xs-4">
                <label for="options" class="col-xs-4">Options</label>
            </div>
            <div class="col-xs-8">
                <div class="row" *ngFor="let group of groups">
                    <div class="col-xs-4" *ngFor="let option of group">
                        <input id="" formControlName="" type="checkbox" [checked]=false /> 
                    </div>
                </div>
            </div>
        </div>
    </div>
    <br />
    <div *ngIf="!ReportsForm.valid">At least one order must be selected</div>
    <button>submit</button>
</form>

Component:

import { Component } from '@angular/core';
import { ReactiveFormsModule, FormBuilder, FormGroup, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import { asEnumerable } from 'linq-es2015';

@Component({
    selector: 'app-report',
    templateUrl: './report.component.html',
    styleUrls: ['./report.component.scss']
})
export class ReportComponent {


    options = [
        { id: 1, option: 'chk 1' },
        { id: 2, option: 'chk 2' },
        { id: 3, option: 'chk 3' },
        { id: 4, option: 'chk 4' },
        { id: 5, option: 'chk 5' },
        { id: 6, option: 'chk 6' },
        { id: 7, option: 'chk 7' },
        { id: 8, option: 'chk 8' },
        { id: 9, option: 'chk 9' },
        { id: 10, option: 'chk 10' },
        { id: 11, option: 'chk 11' },
        { id: 12, option: 'chk 12' },
        { id: 13, option: 'chk 13' },
        { id: 14, option: 'chk 14' },
        { id: 15, option: 'chk 15' },
        { id: 16, option: 'chk 16' },
        { id: 17, option: 'chk 17' },
        { id: 18, option: 'chk 18' }
    ]; 

    constructor(private formBuilder: FormBuilder) {
    } 

    ngOnInit() {

        var groups = asEnumerable(this.options)
            .Select((option, id) => { return { option, id }; })
            .GroupBy(
                x => Math.floor(x.id / 3),
                x => x.option,
                (key, options) => asEnumerable(options).ToArray()
            )
            .ToArray();

    }

    submit() {

//capture selected values
    }
}




Angular 6 Reactive Form - how to add dynamic checkboxe to 3 columns

I am creating dynamic checkbox in a reactive form. For the sake of demo, I have some static data but eventually will use service. Since there can be long list of items for checkbox, I want to display them in 3 columns. I tried changing the css, but I have idea how to achieve this. Template:

<form [formGroup]="ReportsForm" (ngSubmit)="submit()">

    <!--Check boxes-->
    <div class="cb-wrapper" [ngClass]="{'cb-vertical':!tmp}">
        <label formArrayName="orders"
               *ngFor="let order of ReportsForm.controls.orders.controls; let i = index">
            <input type="checkbox" [formControlName]="i">
            
        </label>
    </div>
    <br />

    <div *ngIf="!ReportsForm.valid">At least one order must be selected</div>
    <button>submit</button>
</form>

Code in component

import { Component } from '@angular/core';
import { ReactiveFormsModule, FormBuilder, FormGroup, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import { asEnumerable } from 'linq-es2015';

@Component({
    selector: 'app-report',
    templateUrl: './report.component.html',
    styleUrls: ['./report.component.scss']
})
export class ReportComponent {

    ReportsForm: FormGroup;
    orders = [
        { id: 1, name: 'chk 1' },
        { id: 2, name: 'chk 2' },
        { id: 3, name: 'chk 3' },
        { id: 4, name: 'chk 4' },
        { id: 5, name: 'chk 5' },
        { id: 6, name: 'chk 6' },
        { id: 7, name: 'chk 7' },
        { id: 8, name: 'chk 8' },
        { id: 9, name: 'chk 9' },
        { id: 10, name: 'chk 10' },
        { id: 11, name: 'chk 11' },
        { id: 12, name: 'chk 12' },
        { id: 13, name: 'chk 13' },
        { id: 14, name: 'chk 14' },
        { id: 15, name: 'chk 15' },
        { id: 16, name: 'chk 16' },
        { id: 17, name: 'chk 17' },
        { id: 18, name: 'chk 18' }
    ];

    tmp: boolean = false;
    constructor(private formBuilder: FormBuilder) {
        // Create a new array with a form control for each order. All selected to true by default
        const controls = this.orders.map(c => new FormControl(true));
        this.ReportsForm = this.formBuilder.group({
            orders: new FormArray(controls)
        });
    } 

    ngOnInit() {
    }

    submit() {
        const selectedOrderIds = this.ReportsForm.value.orders
            .map((v, i) => v ? this.orders[i].id : null)
            .filter(v => v !== null);
        console.log(selectedOrderIds);
    }
}




How to change the value of my CheckBox in another activity every time it's clicked

In my main activity there is a button and a textview. When the button is clicked, the textview is changed based on whether or not a checkbox is checked in my second activity. The way it is now, i have to close and reopen the app every time i click the checkbox if i want the changes to apply to my textview. how do i apply the changes every time the checkbox is clicked?

Below are examples of my codes.

My main activity code:

public class MainActivity extends AppCompatActivity {
private Button button;
private TextView textView;

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

    button = findViewById(R.id.button);
    textView = findViewById(R.id.textView);


    SharedPreferences sharedPrefs = getSharedPreferences("com.company.aadne.sharedprefererences", MODE_PRIVATE);
    final Boolean state = sharedPrefs.getBoolean("checkBox1Key", false);


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        if (state){
            textView.setText("Hello");
        }
        else{
            textView.setText("Goodbye");
        }
        }
    });

}

public void launchMain2Avtivity(View view) {
    Intent intent = new Intent(this, Main2Activity.class);
    startActivity(intent);
}

}

My second activity code:

public class Main2Activity extends AppCompatActivity {

private CheckBox checkBox1;

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

    checkBox1 = findViewById(R.id.checkBox1);

    SharedPreferences sharedPref = this.getSharedPreferences("com.company.aadne.sharedprefererences", MODE_PRIVATE);
    final SharedPreferences.Editor editor = sharedPref.edit();
    editor.putBoolean("checkBox1", false);
    editor.commit();

    final boolean checkBox1Checked = sharedPref.getBoolean("checkBox1Key", false);
    checkBox1.setChecked(checkBox1Checked);

    checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            editor.putBoolean("checkBox1Key", isChecked);
            editor.commit();
        }
    });

}

Thanks for any help!




CSS - Label & checkbox not aligning same as other labels and checkbox

I'm making a small survey and my "checkbox-label" & checkboxes will not align the same as the other labels. All the labels have the same class. I need it to align the same as the others.

Here is a link to my codepen to show you what I mean:

https://codepen.io/Saharalara/pen/xMGqPa

The HTML:

<div class="rowTab">
            <div class="labels">
              <label id="checkbox-label" for="changes">What do you think we should do to improve our fabulous toilet if any...</br>there should'nt be any but choose please:</label>
            </div>
              <div class"rightTab">
                <ul id="changes">
                  <li class="checkbox"><label><input name="prefer" value="1" type="checkbox" class="userRatings">Cleanliness</label></li>
                  <li class="checkbox"><label><input  name="prefer" value="2" type="checkbox" class="userRatings">Friendliness</label></li>
                  <li class="checkbox"><label><input  name="prefer" value="3" type="checkbox" class="userRatings">Everything, it's shite</label></li>
                  <li class="checkbox"><label><input  name="prefer" value="4" type="checkbox" class="userRatings">Nothing, it's fantastic</label></li>
                  <li class="checkbox"><label><input  name="prefer" value="5" type="checkbox" class="userRatings">No changes required, it's is the best toilet I've ever been to</label></li>
                 </ul>
            </div>
             </div>

The CSS:

.labels{
  display: inline-block;
  text-align: right;
  vertical-align: top;
  margin-top: 20px;
  width: 40%;
  padding: 5px;
  }

.rightTab{
  display: inline-block;
  text-align: left;
  margin-top: 20px;
  vertical-align: middle;
  width: 48%;
  padding: 5px;
    }

.radio, .checkbox{
  position: relative;
  left: -44px;
  display: block;
  padding-bottom: 10px;
    }




How do I make a jQuery script that changes Image preview based on checkboxes and radio outputs at the same time?

I am very new to coding and I would need a help to write a script that would change the image based on what the user chooses, and at the end provide a download based on the combination from the checkboxes..

I have no idea how to write such script as a newbie.. could anyone help?

Here is an preview of the site: https://imgur.com/a/yWKM6rq

<div class="row">
<div class="craft-style" align=left>
<h2></h2>
</div>
<div class="craft-style" align=left>
<h2>CHOOSE BACKGROUND</h2>
<input type="radio" name="background" value="CLEAN"> KEEP CLEAN BACKGROUND<br>
<input type="radio" name="background" value="PANORAMA"> KEEP PANORAMA OVERLAY ON BACKGROUND<br>
<h2>ADD LAYERS</h2>
<input type="radio" name="pick" value="allcallouts"> ENABLE SPECTATOR CALLOUTS<br>
<input type="radio" name="pick" value="speccallouts"> ENABLE BIG MAP CALLOUTS<br>
<input type="radio" name="pick" value="nocallouts"> DISABLE CALLOUTS<br>
<input type="checkbox" name="choose" value="patterns"> PATTERNS<br>
<input type="checkbox" name="choose" value="buyzones"> BUYZONES<br>
</div>
<div class="craft-style" align=left>
<h2>PREVIEW</h2>
</div>
    </div>

In the end i would like it to be working "crafting" section that allows user to make their custom file(s)




samedi 26 janvier 2019

handle checkbox with "new FormControl"

Basically I do not know how to handle this topic from an *ngFor where there is checkbox. I would normally know how to do it with a [(ngModel)], but I do not know how to do it with reactive forms. I want to associate my checkbox according to what I have in the variable "aUsers" and mark the elements that I have in the "check" attribute. what should I do?

this.ValidacionReunion = new FormGroup({
  observaciones:new FormControl(null, []),
  arrayElements: new FormControl.array([])  //this is the name of my checkboxlist
});

aUsers:any=
[
  {
    "name":"xds",
    "userusuario":2,
    "check":true
  },
  {
    "name":"xdsx",
    "iduser":2,
    "check":false
  }      
]

. . .

<!-- obviously this is inside:<form [formGroup] = "ValidationReunion"> -->
<li  class="list-group-item waves-light"  *ngFor="let user of aUsers" >
 <input type="checkbox" formControlName="user.check">       
</li>




Only check the checkbox if the value of ngModel is true

When my checkbox is clicked the value of my ngModel produto.checked is set to true, but in a moment this value is changed to false without a click in the checkbox. How can i make my checkbox only check/uncheck according by my ngModel?

I try something like:

<tr *ngFor="let produto of sortedDataProduto; let i = index">
   <input [checked]="produto.checked" [(ngModel)]="produto.checked" name="checkedproduto" type="checkbox">
</tr>




How to clear controls i.e. TextBoxes, ComboBoxes, CheckBoxes etc. inside a panel control in C#

I have a form with TextBoxes, ComboBoxes, CheckBoxes, DataGridView inside a panel. On a Button Click event I have the following procedure to clear the controls:

public void ClearControlValues(Control Container)
    {
        try
        {
            foreach (Control ctrl in Container.Controls)
            {
                if (ctrl.GetType() == typeof(TextBox))
                {
                    ((TextBox)ctrl).Text = "";
                }

                if (ctrl.GetType() == typeof(ComboBox))
                {
                    ((ComboBox)ctrl).SelectedIndex = -1;
                }

                if (ctrl.GetType() == typeof(CheckBox))
                {
                    ((CheckBox)ctrl).Checked = false;
                }

                if (ctrl.GetType() == typeof(DateTimePicker))
                {
                    ((DateTimePicker)ctrl).Text = "";
                }

                if (ctrl.GetType() == typeof(DataGrid))
                {
                    ((DateTimePicker)ctrl).Text = "";
                }

                if (ctrl.Controls.Count > 0)
                {
                    LockControlValues(ctrl);
                }

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

Button Click calling:

ClearControlValues(this);

But: Controls inside my panel "MainPanel" is not clearing. What do I am missing?




vendredi 25 janvier 2019

How can I disable all checkboxes on webpage at once?

I have several sets of checkboxes on a webpage. I want to uncheck them all with javascript. Right now, I do it by looking for the names of each set and unchecking them with FOR loops like this...

    for (i=0;i<document.getElementsByName("myboxes").length;i++) {
document.getElementsByName("myboxes")[i].checked=false;}

for (i=0;i<document.getElementsByName("moreboxes").length;i++) {
document.getElementsByName("moreboxes")[i].checked=false;}

for (i=0;i<document.getElementsByName("evenmoreboxes").length;i++) {
document.getElementsByName("evenmoreboxes")[i].checked=false;}

I'm looking for a way to target them all with one loop. I could do getElementsByTagName('input') to target all INPUTS, but that's a problem because I have some radio inputs that I don't want to uncheck. Is there a way to target all checkbox inputs?




DataTables checkboxes can't be clicked

I have a DataTables column that's populated with checkboxes, but for some reason I can't click on any of them.

As far as I can tell my DataTables syntax is fine, so I'm not sure what part of my code is acting up.

Here's a JS Bin. Note: The original JSON file is local, but for Fiddle purposes I added a condensed version. Also, I couldn't get the table data to display, not sure why, so I'll be providing a screenshot in a little bit.

JS snippet:

$('#table-id').DataTable( {
      columns: [
        { data: "Titles" },
        { data: "Categories" },
        { data: "Blank" } // ----------------- Populates rows with checkboxes
      ],
      columnDefs: [
        {
          className: "select-checkbox",
          orderable: false,
          targets: 2
        }
      ],
      data: tableRes, 
      pageLength: 100,
      paging: true,
      pagingType: "full_numbers",
      responsive: true,
        scrollCollapse: true,
        scrollX: true,
        scrollY: 600,
      select: {
        selector: "th:first-child",
        style: "os"
      },
      stateSave: true
    });




Problem with checkbox state after marking everyone as checked

When I try to mark single checkboxes, it works. IF I then mark the topbox that changes everyone to marked, it also works. But when I try to undo the marks, everyone gets unmarked, except for the ones i clicked before clicking the "check everyone" box.

Ive tried editing state and fixing the input in the button. But it doesnt seem to work, no matter what.

handleOnClick = (idx, checked) => {
            this.setState( {
                checked: {
                    ...this.state.checked,
                    [idx]: checked
                },
            })
    }


//For columns
<Checkbox id="headerCheckbox"
                 defaultChecked={false}
                 onClick={this.handleOnClick.bind(this,'all', !checked.all)}
                 checked={checked.all || false}
                 onChange={() => {}}
/>

//for rows
<Checkbox id={row._id} defaultChecked={false}
                onChange={() => {}}
                onClick={this.handleOnClick.bind(this, index, !checked[index])}
                checked={checked[index] || checked.all || false}
  />

Expected result is that if I click on some of my boxes for rows, then the column one, it should mark everyone, which it does. When I then click again, its supposed to uncheck all the boxes in my table, but it only unchecks the ones I did not click before I clicked the "mark everyone" box




On edit trigger that inserts timestamp dependant on checkbox value

I'm trying to develop an inventory sheet for my company I work for in Google Sheets. In the system, I'm wanting if a checkbox in Column C is ticked it will display the "checked out time" in Column D, and if unticked will display the "checked in time" in Column E. However, I'm wanting when the item is checked in, the checked out date/ time cell turns back to blank.

I've used this custom function script to create a TIMESTAMP function that works, but every time the spreadsheet is reopened is recalculates all the date to the current date/time. Any way of making it non-volatile?

function timestamp() {
  return Date();
}

Would I need a onedit trigger that could do what I described above?

WARNING: I'm not scripting savvy at all.I've been scouring the forums for the past week and can't get anything that works. Any help would be greatly appreciated :D

Link: https://docs.google.com/spreadsheets/d/1Oj6eustjvk9opXFNR2jHa0uMjPnKVXsvwOxFjb1t7-8/edit?usp=sharing




Syncing checkboxes from two forms that are dynamically generated in jQuery

I am trying to synchronise two forms with checkboxes that both contain the same amount of checkboxes, so I am trying to link them. The reason is, so I can hide one form and use the other form to send information to the API. The checkboxes are generated through an API, so I can not use hardcoded ID's. I can however link them with the value of the first set of checkboxes, and in the second form, I give the checkboxes the same ID as the value in the first form of checkboxes. However, I am struggling to sync the two.

The second problem is to sync the checkboxes on the first form, with the second form on page load (the idea is that a user can edit his/hers preferences).

I have tried putting the checkboxes of the second form (which will be visible) in an array, and then with loop through the array and check if it can find the value from the first form of checkboxes (which will be invisible).

$('.rss-feed-checkboxes').on('change', function() {

        var rssCheckboxesChecked = [];
        $('.rss-feed-checkboxes:checked').each(function(){
            rssCheckboxesChecked.push($(this).attr('id'));
        });
        console.log( rssCheckboxesChecked ); 

        rssCheckboxesChecked.forEach(element => {

            if ($('.mc-form-checkboxes').val() ==     
$(this).attr('id').toLowerCase()) {
                $('.mc-form-checkboxes').attr('checked',true);
            }    

        });

    });

My expected results are to synchronise the checkboxes on both forms, using the value of the checkboxes in one form, and the ID of the checkboxes in the other form, both forms dynamically generated. The actual result now is a bit messy, when I change some things, sometimes nothing is checked, or sometimes all boxes are checked.




Multiple Checkbox value appear in table view using onchange in javascript

I want to display my checkbox values when I click, Whenever change checkbox, values update on a table view. Here is my code:

<!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="utf-8">
        <title>Get Values of Selected Checboxes</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <label for="checkbox1"> <input class="checkme" type="checkbox" value = "1111" id="checkbox1"> Checkbox 1</label><br>
        <label for="checkbox2"> <input class="checkme" type="checkbox" value = "2222" id="checkbox2"> Checkbox 2</label><br>
        <label for="checkbox3"> <input class="checkme" type="checkbox" value = "3333" id="checkbox3"> Checkbox 3</label><br>
        <label for="checkbox4"> <input class="checkme" type="checkbox" value = "4444" id="checkbox4"> Checkbox 4</label><br>
        <label for="checkbox5"> <input class="checkme" type="checkbox" value = "5555" id="checkbox5"> Checkbox 5</label><br>
        <label for="checkbox6"> <input class="checkme" type="checkbox" value = "6666" id="checkbox6"> Checkbox 6</label><br>
        <label for="checkbox7"> <input class="checkme" type="checkbox" value = "7777" id="checkbox7"> Checkbox 7</label><br>
        <script>
             $(document).on('change', '.checkme', function () {
                var label = $(this).parent();
                if ($(this).prop('checked')) {
                    var checkBox = document.getElementById("checkbox").value;
                    alert(checkBox);

                } else {
                     alert(checkBox);
                }

            });
        </script>

Select each checkbox value display as a table view. The result will appear on the same page.

The result like this:
----------------------------
Value
----------------------------
My Check Box Value is: 1111
My Check Box Value is: 2222
My Check Box Value is: 3333
My Check Box Value is: 4444
----------------------------




jeudi 24 janvier 2019

Pure CSS Checkbox button with no label

I'm trying to replace a checkbox and make it into a button. I've done this before, but for this site I'm using Easy Digital Downloads Front End Submissions. I've searched and searched, also gone through multiple posts here on the site.

I don't know how this was made, but I can't seem to wrap my head around it as the label seems to come before the class. It has this selectit class I've been trying to mess around with, but whatever I do I can't make a button.

When I try something like input[type=checkbox] + label it doesn't actually affect anything. Other examples would be .selectit input[type=checkbox]:before This one works. As well as .selectit input:checked:after But again, I can't add anything with + label it seems.

Well I can make one that has a hover, but not one with a checked state and a color change for example.

I should note that I cannot change any HTML. The way the checkbox is built, I have to stick with, so I'm trying to make a pure CSS solution.

Here's the HTML for the checkboxes. I only really want the parent checkbox to be affected by the hover and checked state.

<ul class="fes-category-checklist">
  <li id="download_category-156" data-open="false" style="display: list-item;"><label class="selectit"><input value="156" type="checkbox" name="download_category[]" id="in-download_category-156"> 2D Assets</label>
    <ul class="children">

      <li id="download_category-183" data-open="false"><label class="selectit"><input value="183" type="checkbox" name="download_category[]" id="in-download_category-183"> Motion Graphics</label></li>

      <li id="download_category-163" data-open="false"><label class="selectit"><input value="163" type="checkbox" name="download_category[]" id="in-download_category-163"> HDRI</label></li>

      <li id="download_category-162" data-open="false"><label class="selectit"><input value="162" type="checkbox" name="download_category[]" id="in-download_category-162"> Materials</label></li>

      <li id="download_category-161" data-open="false"><label class="selectit"><input value="161" type="checkbox" name="download_category[]" id="in-download_category-161"> Textures</label></li>
    </ul>
  </li>
</ul>

I hope someone has some answers Thanks!




JQuery Show/Hide UL children and unselect other parents checkbox

I'm going to do my best to describe my problem. This community has helped me before, so I'm hoping someone will be kind enough to lend me their help once again. I don't really know much about JQuery.

We're setting up a wordpress site using Easy Digital Downloads, because of that we have some restrictions, like not being able to change the HTML, but we can add add JQuery elements on a page.

This is for a category selection system where a user should be able to select only 1 parent category and multiple sub categories under that parent.

I'm looking for a JQuery solution for the following scenario.

We have 5, potentially 6, "categories". These categories have sub categories represented by a UL. By default the sub categories should be hidden. When you click a parent category it should display the sub categories below. If you at any point click the same parent category, it should unselect all children and hide them again.

I also only want 1 parent category to be selected at any given point.

Let me give you a scenario. You click on Cat A, it expands and shows 4 sub categories. You click 2 of those sub categories. You change your mind and instead click on Cat B. This should then hide the sub categories of Cat A and unselect the children, as well as the parent of Cat A.

Just if I haven't made it clear enough, it's important that you can never select a sub category without a parent category.

I've made a basic fiddle with something I found in another thread. Just is just for showing and hiding (though I haven't added a class for hiding yet) This has the html structure we're using.

Another issue is that all of the parent categories use the same class for the children (.children)

$('#in-download_category-156').click(function() {
  $(".children").toggle(this.checked);
});

FIDDLE

I know this is a big ask, so I appreciate any help you can throw my way! Thank you




How to toggle all list items that are not equal to a specific text/category?

I have a HTML list and want to filter for a specific category. At example my list is:

<ul class="myList">
  <li class="list-choose">
      <input class="input-choose" type="checkbox" id="[ID]" name="ID[]"/>
      <label class="label-choose" for=[ID]></label>

      <div class="subtitle">
         <span class="category">[category]</span>
      </div>
  </li>
</ul>

(all in all there are about 40 list items, which should get filtered by category selection)

Now I want to create a category filter (in form of checkboxes/buttons/..) so that you can choose what category you want to display and hide all other elements that aren't in that selected category. My list items are created by an array ( a.e. [category]) so that the list item has its own category. But how can I filter only the selected category? I hope anyone can help me because my Javascript knowledges aren't the best.

Thank you!




Laravel DataTables trigger a checkbox

I am using Laravel with DataTables to display data, the first column of my table is checkboxes and the last one is buttons.

Controller:

function getdata()
    {
     $pdrs = Pdrs::select('ID_Piece', 'Designation', 'Status');
     return DataTables::of($pdrs)
            ->addColumn('checkbox', '<input type="checkbox" name="pdr_checkbox[]" class="pdr_checkbox" value="" />')
            ->rawColumns(['checkbox','action'])
            ->addColumn('action', function($pdr){
                return '<a href="#" class="btn btn-xs btn-primary Ajouter_au_panier" id="'.$pdr->ID_Piece.'"><i class="glyphicon glyphicon-shopping-cart"></i> Ajouter au panier</a>';})
            ->make(true);            
    }

function postdata(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'ID_User'   => 'required',
            'Piece_name'     => 'required',
            'ID_Ligne'  => 'required',
            'order'     => 'required',
        ]);

        $error_array = array();
        $success_output = '';
        if ($validation->fails())
        {
            foreach($validation->messages()->getMessages() as $field_name => $messages)
            {
                $error_array[] = $messages;
            }
        }
        else
        {
            if($request->get('button_action') == "insert")
            {
                $pdr = new Panier([
                    'ID_User'     =>  $request->get('ID_User'),
                    'ID_Piece'    =>  $request->get('Piece_name'),
                    'ID_Ligne'    =>  $request->get('ID_Ligne'),
                    'order'       =>  $request->get('order')
                ]);
                $pdr->save();
                $success_output = '<div class="alert alert-success">Commande ajouté</div>';
            }            

        }
        $output = array(
            'error'     =>  $error_array,
            'success'   =>  $success_output
        );
        echo json_encode($output);
    }

View:

    $(document).ready(function() {
     $('#pdr_table').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": "",
        "columns":[
            { "data": "checkbox", orderable:false, searchable:false},
            { "data": "ID_Piece" },
            { "data": "Designation" },
            { "data": "Status" },
            { "data": "action"}
        ],
        //"order": [[ 0, "asc" ]],
        'rowCallback': function(row, data, index){ 
            if(data.Status == 'Disponible'){ 
                $(row).find('td:eq(3)').css('background-color', 'green').css('color', 'white'); 
            }
            if(data.Status == 'Indisponible'){ 
                $(row).find('td:eq(3)').css('background-color', 'red').css('color', 'white'); 
            } 
        }
     });    

        $(document).on('click', '.pdr_checkbox', function(){//How to color the entire line and get all the values of that line when checked an do the opposite when unchecked?

    });

$(document).on('click', '.Ajouter_au_panier', function(){//form_popup_when_click_on_button_from_the_last_column
    $('#pdrModal').modal('show');
    $('#pdr_form')[0].reset();
    $('#form_output').html('');
    $('#piece').text('PDR'); 
});

$('#pdf_form').on('submit', function(event){//How to get all the values ​​of the line corresponding to the button clicked?
    event.preventDefault();
    var form_data = $(this).serialize();
    $.ajax({
        url:"",
        method:"get",
        data:form_data,
        dataType:"json",
        success:function(data)
        {
            if(data.error.length > 0)//Check the required fields if empty
            {
                var error_html = '';
                for(var count = 0; count < data.error.length; count++)
                {
                    error_html += '<div class="alert alert-danger">'+data.error[count]+'</div>';
                }
                $('#form_output').html(error_html);
            }
            else//no empty field
            {                            
                $('#form_output').html(data.success);
                $('#pdr_form')[0].reset();
                $('#pdr_table').DataTable().ajax.reload();
            }
        }
    })
});

How to hover the line when check the box and do the opposite when uncheck it and get all the values of the corresponding line?

How to get all the values ​​of the line corresponding to the button clicked?




mercredi 23 janvier 2019

How do i pass the value of a CheckBox to another activity?

I am very new to this, and there is probably a simple solution, but i've been trying for two days and can't figure it out. thus my first ever post:

I have two activities. In the first activity there's a CheckBox. If that CheckBox is clicked i want a TextView in my second activity to display a text when i press a Button. Whenever i press that button, the app crashes. I have tried using different Intent variations to pass the CheckBox value to the second actiity. Also, i have tried putting the CheckBox in the same activity as the TextView and Button, and that works fine, but the CheckBox has to be in another activity. Is there a simple solution i am not seeing?

Also, i don't want to use StartActivity(). I just want the Button in my first activity to know if the CheckBox in my second activity is ticked.

Thanks for any advice!




Wicket CheckBox change visibility of other component

I have a Wicket 7 CheckBox and a hidden DateTextField. When I click on a CheckBox I want the DateTextField to be appeared and vice versa. For this reason I have added the DateTextField in a WebMarkUpContainer. If possible I dont want to use Ajax. The problem is that the WebMarkUpContainer is always hidden. In general my code is as follows:

class ResultsPanel extends Panel{

private static final class ResultsPage {

final DateTextField startDate = new DateTextField("startDate",  new DateTextFieldConfig().withLanguage("el");

final CheckBox checkBox = new CheckBox("checkBox");

final WebMarkupContainer wmc = new WebMarkupContainer("wmc");

   // bla bla bla

public Results(String id, CompoundPropertyModel propertyModel) {

            super(id, propertyModel);            
            add(checkBox);  
            wmc.setOutputMarkupPlaceholderTag(true);                     
            wmc.add(startDate);
            add(wmc.setVisible(false));  
            }

public S5ExamsResultsPanel(String id){
  super(id);   
  add(new ResultsPage("resultsPage", new CompoundPropertyModel()));
}

}




How to get the value dynamically created checkbox value in asp.net gridivew

hi im adding checkbox controls dynamically in asp.net gridview like this

         '  CheckBox cb1 = new CheckBox();
            cb1.Text = row.Cells[3].Text;
            row.Cells[3].Controls.Add(cb1);

and i want to access that checkbox is checked or not on button click event....

Any one Help me...

 on button click i am try this 
            foreach (GridViewRow item in grdreport.Rows)
            {
                if (item.RowType == DataControlRowType.DataRow)
                {
                    CheckBox checkbox1 = (CheckBox)item.FindControl("cb1");
                   // cb1.Checked = true;
                    if (checkbox1.Checked)
                    {
                    }
                }
            }

but it gives me error Object reference not set to an instance of an object cb1 value is null




Laravel DataTables multiple select with checkboxes

I am developing an application in Laravel with DataTables where i display data form Mysql database. How to do multiple selection with line color for each selection ? like this link but with multiple selection and how to get values from the selected line ?

This is a screenshot of the app:

enter image description here

Here is code:

$(document).ready(function() {
 $('#pdr_table').DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": "",
    "columns":[
        { "data": "checkbox", orderable:false, searchable:false},
        { "data": "ID_Piece" },
        { "data": "Designation" },
        { "data": "Status" },
        { "data": "action"}
    ],
    //"order": [[ 0, "asc" ]],
    'rowCallback': function(row, data, index){ 
        if(data.Status == 'Disponible'){ 
            $(row).find('td:eq(3)').css('background-color', 'green').css('color', 'white'); 
        }
        if(data.Status == 'Indisponible'){ 
            $(row).find('td:eq(3)').css('background-color', 'red').css('color', 'white'); 
        } 
    }
 });    

$(document).on('click', '.Ajouter_au_panier', function(){
    $('#pdrModal').modal('show');
    $('#pdr_form')[0].reset();
    $('#form_output').html('');
    $('#piece').text('PDR'); 
});

$('#pdr_form').on('submit', function(event){
    event.preventDefault();
    var form_data = $(this).serialize();
    $.ajax({
        url:"",
        method:"get",
        data:form_data,
        dataType:"json",
        success:function(data)
        {
            if(data.error.length > 0)
            {
                var error_html = '';
                for(var count = 0; count < data.error.length; count++)
                {
                    error_html += '<div class="alert alert-danger">'+data.error[count]+'</div>';
                }
                $('#form_output').html(error_html);
            }
            else
            {                            
                $('#form_output').html(data.success);
                $('#pdr_form')[0].reset();
                $('#pdr_table').DataTable().ajax.reload();
            }
        }
    })
});




Hide dropdown option based on checkbox

I'm in a wordpress environment, I have created some filtered post views using the plugin facet WP and I have placed two checkboxes and a dropdown filter.

So I have these 2 checkboxes:

<div class="facetwp-facet facetwp-facet-isola facetwp-type-checkboxes" 
data-name="isola" data-type="checkboxes">
    <div class="facetwp-checkbox" data-value="cefalonia">Cefalonia <span 
class="facetwp-counter">(11)</span>
    </div>
    <div class="facetwp-checkbox" data-value="corfu">Corfù <span     
class="facetwp-counter">(28)</span>
    </div>
</div>

And then I have this dropdown already populated by the plugin:

<div class="facetwp-facet facetwp-facet-localita_di_corfu facetwp-type- 
dropdown" data-name="localita_di_corfu" data-type="dropdown">
<select class="facetwp-dropdown">
    <option value="ipsos">Ipsos</option>
    <option value="acharavi">Acharavi</option>
    <option value="dassia">Dassia</option> 
    <option value="gouvia">Gouvia</option> 
</select>
</div>

What I want is:

  • if I select the first checkbox Cefalonia, then show only options "ipsos" and "acharavi" in the dropdown.
  • if I select the second checkbox Corfù then show only options "Dassia" and "Gouvia" in the dropdown.
  • if both are selected show all the related options.

just need a starting point.. I have found how to do this with 2 dropdowns but not with checkboxes.. I'm not so good with javascript many thanks




Loop through checkboxes in VBA

I'm trying to create a code to loop through a userform to see if the checkboxes are checked and then create a PDF of the sheets. However I get the error "object required". I hope you can help me :)

Option Explicit


Sub Get_PDF_Click()

Dim ReportName As String
ReportName = ActiveSheet.Cells(4, 20).Value
Dim OutputPath As String
OutputPath = "T:\5. Fælles\Optima Lancering Version 1.0\6. Oversigtsark\KontoInvest\Historik\"
Dim YYMM As Variant
Dim Name_of_File As Variant
Dim Name As Variant
Dim x1TypePDF As Variant
Dim cbox As CheckBox
Dim FormControlType As Variant
Dim shp As Shape
Dim PDFUserForm As UserForm


YYMM = Format(WorksheetFunction.EoMonth(Now(), -1), "YYMM")

Name = "BankNordik_faktaark" & YYMM
Name_of_File = OutputPath & "BankNordik\" & Name

 '------- LOOP THROUGH CHECKBOXES -------
For i = 0 To 6 'LBound(Kunde_Array) To UBound(Kunde_Array)
    For Each shp In PDFUserForm
    If shp.FormControlType = xlCheckBox _
    And shp.ControlFormat.Value = True Then
            For Each Ws In Worksheets
                If Ws.Name = "Fakta " & Kunde_Array(i + 1, 1) Then
                    ActiveSheet.ExportAsFixedFormat Type:=x1TypePDF, Filename:= _
                    Name_of_File, Quality _
                    :=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
                    :=False, OpenAfterPublish:=False
                End If
            Next Ws
        End If
    'End If
    Next shp
Next i

End sub




How to put a combo box and checkbox inside the datagrid

So i am displaying my data in my datagrid using this:

con.Open();
adap = new SqlDataAdapter("SELECT ID, Course_Description as 
'Course',Student_Name as 'Name', Classroom as 'Room', Seat_Number as 
'Seat No.' from TBL_SeatPlan WHERE Course_Description = '"+ 
cmbCourse.Text +"' ", con);
ds = new System.Data.DataSet();
adap.Fill(ds,"SeatPlan");
dtSeat.DataSource = ds.Tables[0];
con.Close();

what i want to know is how can i put a comboBox and and check box in a specific column like in Course_Description is a comboBox and checkbox before the ID.

i have seen several articles and videos but they seem a bit complicated to understand for beginners like me. i will really appreciate your help.




mardi 22 janvier 2019

Winforms: Incorrect and incomplete checkbox values exported to excel

I have Form1 and Form2 and one class called Savestate. In Form1, I have datagridview1 checkbox column and a label. The label will reflect the equipment name. The checkbox is initially empty. It’s up to the user to check or uncheck the checkboxes. Each checked checkbox will return a P while the unchecked checkbox will return an O. The P and O will be saved in dgv1p_list that I initiated in Savestate when user click button1. This button1 will also save the equipment name and then go to Form2.

In Form2, there is datagridview2 which reflects the equipment name. When user click Button2, the values in the dgv1p_list will be exported to excel columns B to E while their respective equipment name will be exported to column A.

However, with my code below the values exported to excel are incorrect and incomplete. With reference to Checkbox , the first and last row is unchecked so therefore Column B and Column E should be an O. But with reference to Excel, the excel results are incorrect and cells are empty. Below is my code:

Class Savestate

public static List<string> dgv1p_list = new List<string>();

Form 1

public void Intcabin()
    {
        DataGridViewCheckBoxColumn check = new DataGridViewCheckBoxColumn();
        dataGridView1.ColumnCount = 1;
        dataGridView1.Columns[0].Width = 380;
        dataGridView1.Columns[0].Name = "Item";
        string[] row1 = new string[] { "Hello"};
        string[] row2 = new string[] { "Bye"};
        string[] row3 = new string[] { "okay" };
        string[] row4 = new string[] { "thanks" };
        object[] rows = new object[] { row1, row2, row3, row4};
        foreach (string[] rowArray in rows)
        {
            this.dataGridView1.Rows.Add(rowArray);
        }
        check.HeaderText = "Status";
        check.TrueValue = "P";
        check.FalseValue = "O";
        dataGridView1.Columns.Add(check);
    } 

    private void button1_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow dataGridRow in dataGridView1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridRow.Cells[1];
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if (chk != null)
                {
                    Savestate.dgv1p_list.Add(chk.TrueValue.ToString());
                }
                else
                {
                    Savestate.dgv1p_list.Add(chk.FalseValue.ToString());
                }
            }
        }
        this.Hide();
        FormsCollection.Form2.Show();
    }

Form 2

private void button2_Click(object sender, EventArgs e)
 {
     int _lastRow1 = oSheet1.Range["C" + oSheet1.Rows.Count].End[Excel.XlDirection.xlUp].Row + 1;

        for (int i = 0; i < dataGridView2.Rows.Count; i++)
        {
            for (int j = 0; j < dataGridView2.Columns.Count; j++)
            {
                oSheet1.Cells[_lastRow1, 1] = dataGridView2.Rows[i].Cells[0].Value.ToString();
                oSheet1.Cells[_lastRow1, j+2] = Savestate.dgv1p_list[i];
            }
            _lastRow1++;
        }
 }




Unable to get the checkbox selected or not in template driven form (angular 7)

  <input type="checkbox" [name]="filter.filterName" ngModel />

let filterValue: string = testForm.form.value[filter.filterName];

filterValue is always returning empty string checkbox when checked and unchecked

how can i know that checkbox is checked or not in template driven form and no data binding. I need value from testForm:NgForm object ?




Google Sheets Script to Hide Row if Checkbox Checked

I am trying to find a working code that will automatically hide a row if the checkbox in column F of that row is checked.

I have tried every script I have found and nothing seems to work. Unfortunately I am not code savvy and I am unable to find the issue.

This is what I currently have:

function onOpen() {
  var s = SpreadsheetApp.getActive().getSheetByName("Checklists");
  s.showRows(1, s.getMaxRows());

  s.getRange('F2:F200')
    .getValues()
    .forEach( function (r, i) {
    if (r[0] == "TRUE") 
      s.hideRows(i + 1);
    });
}

The sheet I am working on is "Checklists" and the column that contains the checkbox is F. The value of the checkbox is either TRUE or FALSE. If the value is TRUE, I want that row to be hidden.

Can someone please help!!!




How can I display boolean item as checkbox in QTableWidget?

I am fairly new at Pyside, I would like to display a boolean datatype as a checkbox within a tablewidget

I have tried reconstructing the Data with a QTableWidgetItem but it did not work (see commented out section)

rows = [('Test1123456789', False), ('Test2123456789', False), ('Test3123456789', True), ('Test4123456789', True)]

    #rows2 = []

    # self.checkbox2 = QtWidgets.QTableWidgetItem()
    # self.checkbox2.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)

    # #for i in rows:
    #   #print(i)
    #   #if i[1] == False:
    #       #self.newi = self.checkbox2
    #       self.newi = self.newi.setCheckState(QtCore.Qt.Unchecked)
    #       rows2.append((i[0],self.newi))
    #   else:
    #       self.newi = self.checkbox2
    #       self.newi = self.newi.setCheckState(QtCore.Qt.Checked)
    #       rows2.append((i[0],self.newi))

    for row_number, row_data in enumerate(rows):
        self.classestable.insertRow(row_number)
        for colum_number, data in enumerate(row_data):
            colum_number = colum_number +1
            self.checkbox = QtWidgets.QTableWidgetItem()
            self.checkbox.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
            self.checkbox.setCheckState(QtCore.Qt.Unchecked)
            self.classestable.setItem(row_number,0,self.checkbox)
            self.classestable.setItem(row_number,colum_number,QtWidgets.QTableWidgetItem(str(data)))
    self.classestable.resizeColumnsToContents()

I would like to have it return in the table

CheckBox(Unchecked), Test1123456789, CheckBox(Unchecked)
CheckBox(Unchecked), Test2123456789, CheckBox(Unchecked)
CheckBox(Unchecked), Test3123456789, CheckBox(Checked)
CheckBox(Unchecked), Test4123456789, CheckBox(Checked)




Select a div that's not directly next or after a checkbox on :checked [duplicate]

This question already has an answer here:

I just want to make a Filter box, so when you check the checkboxes they hide divs with info.

The problem here is that I don't know how to effect a div not related to the form itself.

I tried every ~, + and > selectors, none of them work.

If I need JavaScript to do this, could you explain me the JS code I need? Like what each line does, I have very basic JavaScript knowledge.

input#first:checked .div1{
  display: none;
}
input#second:checked .div2{
  display: none;
}
input#third:checked .div3{
  display: none;
}
.div1 {
  background-color: green;
  width: 30px;
  height: 30px;
  margin-top: 10px;
}
.div2 {
  background-color: red;
  width: 30px;
  height: 30px;
  margin-top: 10px;
}
.div3 {
  background-color: blue;
  width: 30px;
  height: 30px;
  margin-top: 10px;
}

.webpage_content {
  width: 500px;
  background-color: yellow;
  margin-top: 30px;
  margin-bottom: 30px;
}
<form>
  <input type="checkbox" id="first" name="first" value="first">
  <label for="first">&nbsp; Click to disable div1</label>
  
  <input type="checkbox" id="second" name="second" value="second">
  <label for="second">&nbsp; Click to disable div2</label>
  
  <input type="checkbox" id="third" name="third" value="third">
  <label for="third">&nbsp; Click to disable div2</label>
</form>


<div class="webpage_content">
  Imagine here's some more divs or ul.
</div>


<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>



How to fix loop to check if checkbox is checked, and if so append value to string?

Can't get loop to spit out a string of the values in checked checkboxes.

Basic Javascript.

I've tried to follow various other stackoverflow posts to no avail. This and This seemed to be what was closest to what I'm trying to make work.

The HTML is just a row of

<div class="help-days">MON<br><input type="checkbox" id="d0-field" value="Monday" aria-describedby="avail-help"></div>

I've tried

var element = document.getElementsByClassName('help-days');
for (var i = 0; i <= 6; i++) {
    if (element[i].checked) {
        var day = $('#d' + i + '-field').val();
        days = days + ' ' + day;
    }
}

and

for (var i = 0; i <= 6; i++) {
    var element = document.getElementById('#d' + i + '-field')
    if (element[i].checked) {
        var day = $('#d' + i + '-field').val();
        days = days + ' ' + day;
    }
}

Below example outputs 'Monday Tuesday Wednesday Thursday Friday Saturday Sunday' which leads me to believe there's something about using HTMLCollection and for loops & checking checkboxes that I'm not quite grasping?

for (var i = 0; i <= 6; i++) {
    var day = $('#d' + i + '-field').val();
    if (day) {
        days = days + ' ' + day;
    }
}

I'm trying to create a string that appends a checkbox 'value' to the string, if the checkbox is checked.

Any help appreciated!




set CheckBoxTreeItem to always selected

I'm using a tree view to navigate faster in my printing view. Before the user Is printing a document he can select or deselect columns. Some of the columns are mandatory so what I want to do is that they are always selected, even when the user is trying to deselect them. This is an example of how it looks like. How can I set the selection for an item to true and keep it like that?

public class TreeItemExample extends Application {

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) {
    primaryStage.setTitle("Hello World!");

    AnchorPane root = new AnchorPane();
    TreeView<String> treeView = new TreeView<>();
    CheckBoxTreeItem<String> rootItem = new CheckBoxTreeItem<>("Example");
    CheckBoxTreeItem<String> mandatoryItem = new CheckBoxTreeItem<>("A");
    CheckBoxTreeItem<String> optionalItem = new CheckBoxTreeItem<>("B");

    mandatoryItem.setSelected(true);
    mandatoryItem.selectedProperty().addListener((observable, oldValue, newValue) -> {
        newValue = true;
        mandatoryItem.setSelected(true);
    });
    rootItem.getChildren().addAll(mandatoryItem, optionalItem);
    treeView.setRoot(rootItem);
    treeView.setCellFactory(CheckBoxTreeCell.<String>forTreeView());

    root.getChildren().add(treeView);

    primaryStage.setScene(new Scene(root, 300, 250));
    primaryStage.show();
}

}




Cakephp 3.6.14: Create table form with checkboxes and process data

I want to create a form where there is an array with a checkbox for each row. So the user can select which rows will be processed in the controller.

So I have created the form and the array. Each row of the array has the name of the Task Element and a checkbox to select it:

enter image description here

<h3><?= __('Task Elements') ?></h3>
<?php echo $this->Form->create('AddElement', ['url'=>['action' => 'add',$tasktypeid]]); ?>
<table cellpadding="0" cellspacing="0">
    <thead>
        <tr>
            <th scope="col"><?= $this->Paginator->sort('id') ?></th>
            <th scope="col"><?= $this->Paginator->sort('name') ?></th>
            <th scope="col"><?= $this->Paginator->sort('element_category_id') ?></th>
        </tr>
    </thead>
    <tbody>      
        <?php foreach ($taskElements as $taskElement): ?>      
        <tr>
            <td><?= $this->Number->format($taskElement->id) ?></td>
            <?= $this->Form->hidden('id',['value' => $taskElement->id]); ?>
            <td><?= $this->Form->control(h($taskElement->name), ['type' => 'checkbox']);?></td>
            <td><?= $taskElement->element_category_id != 0 ? $this->Html->link($taskElement->element_category->name, ['controller' => 'ElementCategories', 'action' => 'view', $taskElement->element_category->id]) : '' ?></td>

        </tr>
        <?php endforeach; ?>            
    </tbody>
</table><?php
echo $this->Form->submit('Add');
echo $this->Form->end();?>

But in the controller debug($this->request->getData()); returns this:

[
'id' => '32',
'Library_Element' => '0',
'Library_Element_2' => '0'
]

Which is not correct because 'Library_Element' id is 27 not 32. So it should return an array with 2 rows not an array with 1 row and 3 columns. How I can fix that? And then in the controller I want to iterate the POST data and check for each row if it is checked or not. How I can correctly iterate the data ?




Asp:Repeater Datasouce - Datatable Checkbox inside Repeater. Delete the current row

Couldn't find anything like it. The page has a Repeater, the data source is a datatable. Rows from the page are added to the datatable, then Repeater is updated and displayed on the page. For example, a user has added incorrect information and needs to remove something from Repeater by placing a check mark in the Checkbox. If the Checkbox is checked, the selected data (a row in the datatable ) should be removed from the data source and Repeater should be updated. How can this be implemented and whether it is possible at all? My code:

<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">

            <ContentTemplate>

                    <asp:Repeater ID="Repeater1" runat="server">

                        <ItemTemplate>

                                <asp:TableCell Width="80px" BackColor="#e3a99a"  HorizontalAlign="Right">
                                      <asp:CheckBox ID="cb_GetOut" runat="server" AutoPostBack="true" Checked="false" Text="DeleteRow" style="padding-right:5px" />
                                </asp:TableCell>

                        </ItemTemplate>

                    </asp:Repeater>

            </ContentTemplate>

        </asp:UpdatePanel>


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Page.IsPostBack = False Then

            dtTest_add.Columns.AddRange(New DataColumn(3) {New DataColumn("text1"), New DataColumn("text2"), New DataColumn("text3"), New DataColumn("text4")})

            ViewState("dtTest_add") = dtTest_add

        Else

            dtTest_add = ViewState("dtTest_add")
            Repeater1.DataSource = TryCast(ViewState("dtTest_add"), DataTable)
            Repeater1.DataBind()

        End If

    End Sub


    Protected Sub btn_addTest_Click(sender As Object, e As System.EventArgs) Handles btn_addTest.Click

        dtTest_add.Rows.Add(txt1.Text, txt2.Text, txt3.Text, txt4.Text)

        dtTest_add = ViewState("dtTest_add")

        ViewState("dtTest_add") = dtTest_add
        Repeater1.DataSource = TryCast(ViewState("dtTest_add"), DataTable)
        Repeater1.DataBind()

        UpdatePanel1.Update()

    End Sub


    Protected Sub Repeater1_ItemCreated(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater1.ItemCreated

        Dim cb_GO As CheckBox = CType(e.Item.FindControl("cb_GetOut"), CheckBox)
        ScriptManager.GetCurrent(Page).RegisterAsyncPostBackControl(cb_GO)

    End Sub


    Protected Sub Repeater1_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater1.ItemDataBound

        Dim cb_GO As CheckBox = DirectCast(e.Item.FindControl("cb_GetOut"), CheckBox)

        cb_GO.Attributes("onclick") = "this.checked = (" + dtTest_add + ").deleteRow(" + CStr(e.Item.ItemIndex) + ");"

    End Sub

The "btn_addTest" button is on a form not in Repeater. With it I add data to the data source. Then update the Repeater.

I handle the "onclick" Checkbox event in this line of code

cb_GO.Attributes("onclick") = "this.checked = (" + dtTest_add + ").deleteRow(" + CStr(e.Item.ItemIndex) + ");"

It is necessary to remove data from datatable, and Repeater will simply be updated then and all. But how do you do that? Can't get through to a datatable with the Repeater in ItemDataBound.