samedi 30 juin 2018

(JAVASCRIPT) Pass Value of multiple selected checkboxes into multiple corresponding input fields

I have a code like so;

<label><input type="checkbox" />A</label><br />
<label><input type="checkbox" />B</label><br />
<label><input type="checkbox" />C</label><br />
<label><input type="checkbox" />D</label><br />

<input name="selected_1" />
<input name="selected_2" />
<input name="selected_3" />

$(function() {
    $('input').on('click', function() {
        var values = [];
        $('input:checked').each(function() {
            values.push($(this).parent().text());
        });
        $('[name="selected_1"]').attr({value: values.join(', ')});
    });
});

The code above accurately passes the value of all selected checkboxes (comma-separated) to the input field [selected_1].

However, I want to pass the value of any of the selected checkbox into [name="selected_1"], the second selected checkbox value into [name="selected_2"] and the third selected checkbox to [name="selected_3"] in no given order. Then I want to limit the selection to a maximum of only three check-boxes selected in the form.

This fiddle Limit Checkbox Selection Demonstrates how limiting the selection is achieved.

Now, how do I pass the value of each checkbox selected into the corresponding input field using Javascript or JQuery 3.3.1?

Any help will be greatly appreciated.




How to set a max number of checked boxes

I have a list of option with a corresponding checkbox (Material-UI) And I'm trying to figure out how I Can set a max number on checked boxes (for instance, I would only want the user to be able to click three and then disable the rest) Do I do this in the state?

const styles = theme => ({
  root: {
    width: '100%',
    maxWidth: 260,
    backgroundColor: theme.palette.background.paper,
  },
});

class CheckboxList extends React.Component {
  state = {
    checked: [0],
  };

  handleToggle = value => () => {
    const { checked } = this.state;
    const currentIndex = checked.indexOf(value);
    const newChecked = [...checked];

    if (currentIndex === -1) {
      newChecked.push(value);
    } else {
      newChecked.splice(currentIndex, 1);
    }

    this.setState({
      checked: newChecked,
    });
  };

  render() {
    const { classes } = this.props;
    const toppings = ['Chicken', 'Pineapple', 'Corn', 'Olives (green)', 'Red union', 'Spinach', 'Cherry tomatoes']
    return (
      <div className={classes.root}>
        <List>
          {toppings.map(value => (
            <ListItem
              key={value}
              role={undefined}
              dense
              button
              onClick={this.handleToggle(value)}
              className={classes.listItem}
            >
              <Checkbox
                checked={this.state.checked.indexOf(value) !== -1}
                tabIndex={-1}
                disableRipple
              />
              <ListItemText primary={`NewAge ${value}`} />

            </ListItem>
          ))}
        </List>
      </div>
    );
  }
}

CheckboxList.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(CheckboxList);




vendredi 29 juin 2018

Why does jQuery not see a checkbox has been auto checked?

I have some jQuery checking to see when a human clicks a check button but if the page loads with the button marked as checked already, the jQuery doesn't work.

    $ (function(){
        var requiredCheckboxes = $('.options :checkbox[required]');
        requiredCheckboxes.change(function(){
            if(requiredCheckboxes.is(':checked')) {
                requiredCheckboxes.removeAttr('required');
            } else {
                requiredCheckboxes.attr('required', 'required');
            }
        });
    });

What I need this to do is if the checkbox is already checked, it removes the required attribute. Why is it not working when a variable is posted to the page and PHP adds checked="checked" to the input?

Thanks!




How can you show options in dojo dijit/Dialog and process responses with JavaScript?

I want to use dijit/Dialog to display dynamically generated options (maybe as checkboxes) and capture the user's response. For example, I generate three options to go in the dialog box:

Please pick an option:

Option 1
Option 2
Option 3

After the user indicates options 1, 2 and/or 3, I'd like to use JavaScript to collect those answers and send them (with xhr()) to the server for further processing.

I looked at http://dojotoolkit.org/reference-guide/1.10/dijit/Dialog.html, but I don't see any combination of the examples that would put all this together. Does anyone know of a way to do this?

Thanks!




Angular 4 using checkboxes with data that doesn't include booleans

I have an api that returns data that I need to use with checkboxes. If I am writing an Angular 4 app and my data looks like the code below:

mydata = [{name: 'Clark Kent'}, {name 'Lois Lane'}];

and my html looks like this:

<div class="members-container">
      <mat-card *ngFor="let member of mydata" class="member-card">
        <div class="card-checkbox">
          <mat-checkbox>
            <h4></h4>
          </mat-checkbox>
        </div>
      </mat-card>
</div>

In the controller, I want to use the checkboxes to select members to add to an array. If the api data returned a selected boolean it would be really easy to bind the checkbox to the array. I could manually add a selected field to the data but that extra step would slow down the data displaying on the screen. What is the best way to go about getting the checked members into my array?




DataGridView checkbox doesn't update until another control is clicked on

I implemented a header checkbox (from this answer) for my DataGridView that checks/unchecks all the checkboxes. It works for all checkboxes other than the first one. The first checkbox will only update its state after another control has been clicked on, as seen here:

GIF

And even later I noticed that the checkbox that doesn't update its state is the last checkbox that has been manually clicked on.

enter image description here

To be honest I'm not even exactly sure what's going on. What I tried though was creating an invisible dummy button and PerformClick() it, hoping that it would count as a click on a control and would update the state of the checkbox.

I also looked into Refresh(), Update(), and Invalidate(), but the checkbox cell doesn't have those methods and I couldn't do it.

This function is launched when the header checkbox is checked/unchecked:

private bool selectAllChecked = false;
private void SelectAll(object sender, EventArgs e) {
    selectAllChecked = !selectAllChecked;

    foreach (DataGridViewRow row in myGridView.Rows) {
        DataGridViewCheckBoxCell checkb = (DataGridViewCheckBoxCell)row.Cells["Checkbox"];
        checkb.Value = selectAllChecked;
    }
}




Customize Mat-checkbox inderminate icon

Default Icon for MatCheckbox Inderminate is like below:

Default

I want to customize it to look like this:

Customized checkbox




TreeGrid with interactive checkbox

Is there a way to add checkbox to a TreeGrid? (vaadin 8.1)

I tried "treeGrid.setSelectionMode(SelectionMode.MULTI);" but when I select parent node, this way doesn't select automatically all its children.

Is there a way to do this?

Thank you,




jeudi 28 juin 2018

get values of all checkboxes (checked or unchecked)with same name

I am trying to build a form that lists all available items and users can select some items and enter a value to input element aside the checkbox.

Each checkbox has a input text box aside it.

<?php
    foreach ($items as $item):
        $itemID = $item['item_id'];
        $itemTitle = $item['item'];
?>
    <tr>
        <td>
            <li> 
                <div class="checkbox">
                    <input type="hidden" name="selected_items[]" value="0">
                    <input type='checkbox' name='selected_items[]' value='<?php echo $itemID; ?>'/> 
                <?php echo ucfirst($itemTitle); ?>

                </div>
            </li>
        </td>
        <td><input type='number' name='quantities[]' value="0.00" step="0.01" /> </td>
    </tr>
<?php endforeach; ?>

Here's how the form looks:

Available Items    |  Qty
--------------------------
[] Bread           |  [input]
[] Coffee          |  [input]
[] Egg             |  [input]
[] Cake            |  [input]

I want the two arrays : selected_items[] and quantities to be of the same length as they are so I can combine them.

If unchecked, value should be left to 0.

So, combined_array should look like:

0=>0
Coffee=>44
Egg=>56
0=>0

Can anyone help me with this?




How to see if radio button or checkbox is checked using PDFBox in Java?

I am trying to create a program that reads a PDF Form (questions and answers) and, for now, simply outputs everything back to the screen. My problem is, when I use getValueAsString on radio buttons or check boxes, it always returns an empty string, no matter if it is checked or not. Is there another method I should be using? Here is my code:

public static void listFields(PDDocument doc) throws Exception
{
    PDDocumentCatalog catalog = doc.getDocumentCatalog();
    PDAcroForm form = catalog.getAcroForm();
    List<PDField> fields = form.getFields();

    for(PDField field: fields)
    {
        String name = field.getFullyQualifiedName();
        if (field instanceof PDTextField || field instanceof PDComboBox)
        {
             Object value = field.getValueAsString();
             System.out.print(name);
             System.out.print(" = ");
             System.out.print(value);
             System.out.println();
        }
        else if (field instanceof PDPushButton)
            ;
        else
        {
            if (field instanceof PDRadioButton)
            {
                List<String> exportValues = ((PDRadioButton) field).getSelectedExportValues();
                for (String string : exportValues)
                {
                    name = field.getFullyQualifiedName();
                    System.out.print(name);
                    System.out.print(" = ");
                    System.out.print(string);
                    System.out.println();
                }
            }
            else if (field instanceof PDCheckBox)
            {
                PDButton box = (PDButton)field;
                String value = box.getValue();
                System.out.print(name);
                System.out.print(" = ");
                System.out.print(value);
                System.out.println();
            }

        }
    }
}

public static void main(String[] args) throws Exception {
    File file = new File("C:\\Users\\bobdu\\Documents\\SHIP_CCF_LastName_FirstName_YYYYMMDD_v1_Sample.pdf");
    PDDocument doc = PDDocument.load(file);
    listFields(doc);
}

for(PDField field: fields)
    {
        String name = field.getFullyQualifiedName();
        if (field instanceof PDTextField || field instanceof PDComboBox)
        {
             Object value = field.getValueAsString();
             System.out.print(name);
             System.out.print(" = ");
             System.out.print(value);
             System.out.println();
        }
        else if (field instanceof PDPushButton)
            ;
        else
        {
            if (field instanceof PDRadioButton)
            {
                List<String> exportValues = ((PDRadioButton) field).getSelectedExportValues();
                for (String string : exportValues)
                {
                    name = field.getFullyQualifiedName();
                    System.out.print(name);
                    System.out.print(" = ");
                    System.out.print(string);
                    System.out.println();
                }
            }
            else if (field instanceof PDCheckBox)
            {
                PDButton box = (PDButton)field;
                String value = box.getValue();
                System.out.print(name);
                System.out.print(" = ");
                System.out.print(value);
                System.out.println();
            }

        }
    }
}

public static void main(String[] args) throws Exception {
    File file = new File("C:\\Users\\bobdu\\Documents\\SHIP_CCF_LastName_FirstName_YYYYMMDD_v1_Sample.pdf");
    PDDocument doc = PDDocument.load(file);
    listFields(doc);
}

Thank you in advance for helping me.




Make only checkbox clickable in activeadmin boolean fields

Right now, the boolean fields in the edit forms in activeadmin are rendered so that clicking on the whole row where the checkbox is positioned can change the checkbox value. So not only on the checkbox and its label but also on all the space left and right to it.

But I want to make just the checkboxes clickable, not the entire line. How is it possible to implement this?




CSS: Custom Checkbox doesn't work

I changed my checkboxes with the help of css, it work in Chrome, but not in i.e and edge. So, I found this reference: ref

This is my code:

         .checkbox-style {
            display: none;
        }

        .checkbox-style + label {
            position: relative;
            display: block;
            width: 14px;
            height: 14px;
            border: 1px solid #C0C5C9;
            content: "";
            background: #FFF;
            align-items: center;
        }

        .checkbox-style[type="checkbox"]:checked + label:before {
            font-family: 'FontAwesome' !important;
            content: "\f00c";
            border: none;
            color: #015CDA;
            font-size: 12px;
            -webkit-text-stroke: medium #FFF;
            margin-left: -11px;
        }

And this is the html:

<span class="checkbox-wrapper" role="presentation"> <input type="checkbox" class="checkbox-style"><label></label></span>

The checkbox is appear like I wanted but the :before of the label is not creating when I click on the checkbox. So, my checkboxes are not checkable. Why?




Checkbox count in JSP

I have an error when it comes to checkbox count. I have a checkbox appear next to my data. For example, I ticked 2 checkboxes, and I press delete. It will always appear my count as 0. How do I fix this error ? I have tried several ways to fix this but my count will always display as 0.

This is a picture of the message display

 String[] id = request.getParameterValues("deletechkbox");
        int count=0;
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            // Step 2: Define Connection URL
            String connURL = "jdbc:mysql://localhost/medicloud?user=root&password=root";
            // Step 3: Establish connection to URL
            conn = DriverManager.getConnection(connURL);

            if (id != null)
            {

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

        String sqlStr = "DELETE from exercise1 where id=?";
        PreparedStatement pstmt = conn.prepareStatement(sqlStr);
        pstmt.setInt(3, Integer.parseInt(id[i]));
        int rec = pstmt.executeUpdate();
        if (rec==1)
            count++;
        }
        }




Only one check box to be selected at any one time in gridview

i have added a check box on my grid view. how do i make it so only 1 check box can be selected at any time.

                    <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" Font-Size="Small" Width="100%">
                        <Columns>


                            <asp:BoundField DataField="Supplier" HeaderText="Supplier" SortExpression="Supplier" />
                            <asp:BoundField DataField="Term" HeaderText="Term" SortExpression="Term" />
                            <asp:BoundField DataField="Tariff" HeaderText="Tariff" SortExpression="Tariff" />
                            <asp:BoundField DataField="SC" HeaderText="SC" SortExpression="SC" />
                            <asp:BoundField DataField="Charge" HeaderText="Charge" SortExpression="Charge" />
                            <asp:BoundField DataField="Unit_Rate" HeaderText="Unit_Rate" SortExpression="Unit_Rate" />
                            <asp:BoundField DataField="Day_Rate" HeaderText="Day_Rate" SortExpression="Day_Rate" />
                            <asp:BoundField DataField="Night_Rate" HeaderText="Night_Rate" SortExpression="Night_Rate" />
                            <asp:BoundField DataField="Weekday_Rate" HeaderText="Weekday_Rate" SortExpression="Weekday_Rate" />
                            <asp:BoundField DataField="Eve_Wkend_Rate" HeaderText="Eve_Wkend_Rate" SortExpression="Eve_Wkend_Rate" />
                            <asp:BoundField DataField="Eve_Wkend_Night_Rate" HeaderText="Eve_Wkend_Night_Rate" SortExpression="Eve_Wkend_Night_Rate" />
                            <asp:BoundField DataField="Winter_Rate" HeaderText="Winter_Rate" SortExpression="Winter_Rate" />
                            <asp:BoundField DataField="Other_Rates" HeaderText="Other_Rates" SortExpression="Other_Rates" />
                            <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:CheckBox ID="CheckBox1" runat="server" />
                                </ItemTemplate>
                            </asp:TemplateField>




How Can i do Only one checkbox selected at a time in given list in ngFor in angular 5?

I want to do only one checkbox selected at a time in ngFor in angular 5. i have the following code below.

<div class="form-check" style="margin-top:0;">
   <label class="form-check-label">
    <input class="form-check-input"  id="res" (change)="selectRestaurant(restaurant,i)" [checked]="restaurant.checked" type="checkbox">
        <span class="form-check-sign"></span>
    </label>
</div>

And in my component

selectRestaurant(restaurant: any, i: any) {
    if (restaurant) {
      restaurant.checked = !restaurant.checked;
    }
  }

So any possible solution for only one checkbox selected in given list?




Enable CheckBoxes in one radGrid after checked in other RadGrid in Telerik

I'm using in Telerik. how can I enable CheckBoxes in one radGrid after checked in other RadGrid.

I'm using -- ClientEvents onSelected="func" -- and then I have finction ib JavaScript run on the other RadGrid. I know to to check them all (set_selected(true))

but I dont know how ot enable them all.

Thenks!




Grouping Checkboxes - jQuery / JS / ASP.NET

So I am grouping the checkboxes with data-groupname and use jQuery to auto-select the whole group if one of the group member is checked.

Here's my JS code:

$(document).on("click", checkBoxes, function (e) {
        var isChecked = $(e.target).prop("checked");
        var parent = $(e.target).parent();
        var groupName = $(parent).data("groupname");     
        var chs = $("[data-groupname='" + groupName + "']");

        $(chs).each(function (i) {           
            var chk = $(chs[i]).children().first();

            $(chk).prop('checked', isChecked);           
        })    

This works just fine but I want to limit the .each() to only loop thru the parent of "group name parent" if that makes sense. In other words, I don't want to look for any group-names outside of that table. In my example is looking on the whole page to find the that group name and then if "Parent Group Name" == "groupName" then auto-select / deselect the group or else return true; to continue the loop.

This is my checkbox the ASP markup. What this does, is creating a column of checkboxes, one per each row. The checkboxes are generated dynamically from the code behind (vb.net).

<asp:TemplateField>
  <HeaderTemplate><asp:CheckBox runat="server" Checked="true" /></HeaderTemplate>
  <ItemTemplate><asp:CheckBox runat="server" data-groupname='<%#Eval("InvoiceCreditNumber")%>' Checked="true" ID="chkSelected" /></ItemTemplate>
</asp:TemplateField>

Looking forward for any ideas of what approach to take in order to make this work.

Thanks.




Send value checkbox in mail

i have a problem with send value multi checkbox by mail:

<input type="checkbox" name="wiztype[]" value="value1">
<input type="checkbox" name="wiztype[]" value="value2">
<input type="checkbox" name="wiztype[]" value="value3">
<input type="checkbox" name="wiztype[]" value="value4">
<input type="checkbox" name="wiztype[]" value="value5">

I'm trying to use the plugin for validating form, i have there:

var wiztype = $("input[name='wiztype[]']:checked").serializeArray();

In the mail-proces.php i have:

$wiztype = $_POST["wiztype"];

In the mail I have:

 [object Object],[object Object] (x number of selected boxes)

I tried to do foreach

if(!empty($_POST['wiztype'])) {
foreach($_POST['wiztype'] as $wiztypelist) {
        $wiztypelist;
}
}

What can i do with this? Please help :)




How Add or Remove Checkboxes value from the array?

i want to add or remove value from the array. when i select the checkbox the value will pushed to array. when i unselect the checkbox the value will remove from the array.

CheckBox

<CheckBox
 checked={this.state.currentValue}
onClick={() => this._changeValue(index)}>

onClick function

_changeValue(value) {
    this.setState({
      currentValue: !this.state.currentValue,
    });
   console.log(value)
   selectedQuesiton.push(value)
  }



autosum when click on check in a table? Javascritpt

please help me

I need to know how to make a check in a table add a column with values ​​to cross them, I know what can be done with javascript, but I try and it does not work

some toturial like the following link but with pure javascript

link example : 'codepen.io/anon/pen/MXzyLj'




mercredi 27 juin 2018

Limit number of checked checkboxes for bokeh plot

The following code generates a bokeh plot with checkboxes that can make graphs visible/invisible. It works great, but I would like to know if it's possible to limit the number of allowed checked checkboxes, for example no more than 2 at the time.

import numpy as np
from bokeh.io import output_file, show
from bokeh.layouts import row
from bokeh.palettes import Viridis3
from bokeh.plotting import figure
from bokeh.models import CheckboxGroup, CustomJS

output_file("line_on_off.html", title="line_on_off.py example")

p = figure()
props = dict(line_width=4, line_alpha=0.7)
x = np.linspace(0, 4 * np.pi, 100)
l0 = p.line(x, np.sin(x), color=Viridis3[0], legend="Line 0", **props)
l1 = p.line(x, 4 * np.cos(x), color=Viridis3[1], legend="Line 1", **props)
l2 = p.line(x, np.tan(x), color=Viridis3[2], legend="Line 2", **props)

checkbox = CheckboxGroup(labels=["Line 0", "Line 1", "Line 2"],
                         active=[0, 1, 2], width=100)
checkbox.callback = CustomJS.from_coffeescript(args=dict(l0=l0, l1=l1, l2=l2, checkbox=checkbox), code="""
l0.visible = 0 in checkbox.active;
l1.visible = 1 in checkbox.active;
l2.visible = 2 in checkbox.active;
""")

layout = row(checkbox, p)
show(layout)

I think this can be done in javascript, but I don't know how to acces the javascript involved here. Could I just write javascript and integrate it with my bokeh plot somehow? I would really appreciate the help!




Change status based on checkbox value rails

I have multiple checkboxes(which is for status of a record) in a page, I need to update the status of records while a button is clicked

<% collection.each do |staff| %>
  <div class="col-sm-6 col-md-4 col-lg-3" id="staff-<%= role.id %>">
 <input class="filled-in chk-col-indigo" type="checkbox" id="staffStatus- 
    <%=staff.id %>">
 <label class="labelValue" for="staffStatus-<%= staff.id %>">
<% end%>

when the submit button is clicked I just take all the checkbox based on checked status,

$(document).on 'click', '#StatusUpdateButton', ->
     inactive = []
     active = []
     $.each $(".staff__active:not(:checked)"), ->         
     inactive.push($(this).val())
     $.each $(".staff__active:checked"), ->
     active.push($(this).val())

In controller,

def update_role_status
             Staff.where('id IN (?)', params[:active]).update_all(active: true)
             Staff.where('id IN (?)', params[:inactive]).update_all(active: false)
        end

I am updating the status, But i want to do it with better option, Is that okay to send all the checkbox status or will that be good to send only changed check boxes, I am in confusion to take the better option, Any suggession




Android: Add checkbox to button?

I created a button programmatically:

Button button = new Button(getApplicationContext());
button.setTextSize(30);
button.setGravity(Gravity.START);
button.setText("Button");

Now I want to add a CheckBox to the button. Is there a good way to do this?




Angular 5 - Uncheck all checkboxes function is not affecting view

I'm trying to include a reset button on a Reactive form in Angular 5. For all form fields, the reset is working perfectly except for the multiple checkboxes, which are dynamically created.

Actually the reset apparently happens for the checkboxes as well, but the result is not reflected in the view.

service.component.html

<form [formGroup]="f" (ngSubmit)="submit()">
  <input type="hidden" id="$key" formControlName="$key">
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" formControlName="name">
  </div>
  <br/>
  <p>Professionals</p>
  <div formArrayName="prof">
    <div *ngFor="let p of professionals | async; let i = index">
      <label class="form-check-label">
      <input class="form-check-input" type="checkbox (change)="onChange({name: p.name, id: p.$key}, $event.target.checked)" [checked]="f.controls.prof.value.indexOf(p.name) > -1"/></label>
    </div>
    <pre></pre>
  </div>
  <br/>
  <button class="btn btn-success" type="submit" [disabled]="f?.invalid">Save</button>
  <button class="btn btn-secondary" type="button" (click)="resetForm($event.target.checked)">Reset</button>
</form>

service.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators, FormArray } from '@angular/forms'

import { AngularFireAuth } from 'angularfire2/auth';
import { Router, ActivatedRoute } from '@angular/router';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable} from 'angularfire2/database';
import { Service } from './service';

export class ServiceComponent implements OnInit {

  f: FormGroup;

  userId: string;
  $key: string;
  value: any;
  services: FirebaseListObservable<Service[]>;
  service: FirebaseObjectObservable<Service>;
  professionals: FirebaseListObservable<Service[]>;
  profs: FirebaseListObservable<Service[]>;

  constructor(private db: AngularFireDatabase, 
              private afAuth: AngularFireAuth,
              private route: ActivatedRoute, 
              private router: Router,
              private fb: FormBuilder) { 

    this.afAuth.authState.subscribe(user => {
      if(user) this.userId = user.uid
        this.services = db.list(`services/${this.userId}`);
    })

    this.afAuth.authState.subscribe(user => {
      if(user) this.userId = user.uid
        this.professionals = this.db.list(`professionals/${this.userId}`);
    })

  }

  ngOnInit() {   

    // build the form
    this.f = this.fb.group({
      $key: new FormControl(null),
      name: this.fb.control('', Validators.required),
      prof: this.fb.array([], Validators.required)
    })
  }

   onChange(name:string, isChecked: boolean) {
    const profArr = <FormArray>this.f.controls.prof;

    if(isChecked) {
      profArr.push(new FormControl(name));
      console.log(profArr.value);
    } else {
      let index = profArr.controls.findIndex(x => x.value == name)
      profArr.removeAt(index);
      console.log(profArr.value);
    }
  }

   resetForm(){
    let profArr = <FormArray>this.f.controls.prof;

    this.f.controls.name.setValue('');
    profArr.controls.map(x => x.patchValue(false));
    this.f.controls.$key.setValue(null);
   }
}

service.ts

export class Service {
    $key: string;
    name: string;
    professionals: string[];
  }

The result of the code above, displayed by line <pre> </ pre> is:

When I fill out the form:

{
  "$key": null,
  "name": "Test service",
  "prof": [
    {
      "name": "Ana Marques",
      "id": "-LEZwqy3cI3ZoYykonWX"
    },
    {
      "name": "Pedro Campos",
      "id": "-LEZz8ksgp_kItb1u7RE"
    }
  ]
}

When I click on Reset button:

{
  "$key": null,
  "name": "",
  "prof": [
    false,
    false
  ]
}

But checkboxes are still selected:

enter image description here

What is missing?




Get selected checkboxes values in Angular 5

I have a checkbox list control and am trying to get checked values into an array.

My models:

export class Order {
    Products: Product[];
    SelectedProducts: string[];
}

export class Product {
    Id: number;
    Title: string;
}

The snippet goes through the Product property and displays them as checkboxes:

    <div *ngFor="let product of orderService.order.Products">

        <label>
            <input type="checkbox" name="orderService.order.Products" value="" [(ngModel)]="product.checked" />
            
        </label>

    </div>

I can get the list of orderService.order.Products values from the checkboxes but how to filter them to get only checked values when submitting?

I based my code on the @ccwasden answer here: Angular 2: Get Values of Multiple Checked Checkboxes but my Product model does not have the checked property and it shouldn't have.

In my component I have:

get selectedOptions() {
    return this.orderService.order.Products
        //.filter(opt => opt.checked)
        .map(opt => opt.value)
}

submitorder(form: NgForm) {
    var selection = this.selectedOptions;

    [post order here]
}

but selectedOptions comes empty.




Wordpress checkbox switch element visibilty

Hi! Is there any way to make this checkbox , switch this element, to make it visible and hidden.

And the second question is, can i use for this just Custom CSS & JS plugin.

P.S. these elements were created by Participants Database plugin so i can't change their attributes.




Using indetermined selection checkbox in sap.m.Tree selection

I am using the sap.m.Tree to display the data in Tree format. I want to make selection like this.

  • If the parent node has many items as child in tree. Check box of the parent node should be checked if all the child items selection is checked.
  • If the parent node has many items as child in tree. Check box of the parent node should be unchecked if all the child items selection is unchecked.
  • If the parent node has many items as child in tree. Checkbox of the parent node should be in undetermined state(like checkbox filled with square solid color) if tree has child items in which some of them are checked and some are unchecked. Is there any way to achieve this using sap.m.Tree and in multiselect mode?



mardi 26 juin 2018

How do I update multiple columns in a table with one checkbox?

We're developing an in-house C.M.S. to keep track of our customers, relevant information, and to track issues that those customers have. To that end, we have a couple of columns in our "tickets" table - we have a "completed" boolean, a "completed_at" datetime, and a "completed_by" integer.

We're trying to come up with a couple of U.I. methods by which we could close a ticket - and in the "Edit Ticket" page, we want to have a single checkbox that we could check that would updated all three of those columns:

  1. "completed" from false to true
  2. "completed_at" from null to Time.now
  3. "completed_by" from null to current_user.id

We've tried a couple of different approaches from all over the web, but we're not entirely sure how we'd do this.




Calling checked "checkboxes" only

I don't seem to be familiar with calling objects/elements from the DOM. In my code below i have a variable that collects all the added checkboxes. And now i want to collect only the checked ones once submit is pressed.

                   <form id="name_form">

                    <label for="name">First name: </label>
                    <input id="name" type="text" name="name">
                    <input type="button" id="btnAdd" value="add" onclick="newTextBox(this)"><br>

                    <input type="button" id="btnAdd" value="submit" onclick="printme()">
                  </form>

                  <script>
                      var instance = 1;
                      var allchecked = [];
                      var form = document.forms.name_form;
                      function newTextBox(element) {
                        form = document.forms.name_form;                              // call the form from DOM.
                            if (form.name.value === null) {                           // if name value in the form is empty.
                              console.log("if has: " +form.name.value);               // prove it. :D
                              alert("Insert something in the name department. :)");   // alert me as well.
                          } else {
                            console.log("else has: " + form.name.value);              // prove whatever else it might have.

                                var newInput = document.createElement("input");       // create a new input element.
                                newInput.id = "text" + instance;                      // add an id to it.
                                newInput.name = "text" + instance;                    // add a name to it.
                                newInput.type = "checkbox";                           // add a type of checkbox.
                                newInput.checked = true;                              // turn it's checkbox to true.


                                var label = document.createElement("label");          // create a label for it.
                                label.id = "added";                                   // give an id to the label.
                                label.htmlFor = "text" + instance;                    // what is the label for.
                                label.innerHTML= "Hello " + form.name.value           // insert values from the given name inside the form.

                                instance++;                                           // increment the instance counter.
                                form.insertBefore(document.createElement("br"), element); // insert a brake tag after the add button element.
                                form.insertBefore(newInput,element);                  // insert the new input tag before the add button element.
                                form.insertBefore(label, newInput);                   // insert the label before the input tag element.

                                allchecked.push(label.innerHTML);                     // push value to the label created.
                                form.name.value = null;                               // clear the value in the name entry.
                          }
                      }
                      var chek = [];
                      function printme(){
                          for (i=0; i<form.elements; i++) {
                            if (form.elements[i].checked) {
                              chek.push(form.elements[i])
                            }
                        }
                        console.log(chek);
                      }
                  </script>

Once the Submit button is pressed I need the "chek" list to print with only checked values the way the "allchecked" list does. My "printme()" function is return an empty list. am I using elements wrong.




collection_check_boxes disable checked checkboxes

i have a collection of checkboxes (collection_check_boxes) inside a form_group. i need to disable all checkboxes that are checked on page load. The collection looks like this:

f.collection_check_boxes :should_create, Student.all, :id, :name, checked: @teacher.try(:class).map(&:student_id), disabled: @teacher.try(:class).map(&:student_id), label: "Create class", include_hidden: false

where the collection is the students and the checked students are those that are already in the teacher's class which returns [1, 2, 4]. However, whereas checked: [1,2,4] results in those three checkboxes being checked, disabled: [1,2,4] results in every checkbox being disabled, rather than just those three. How can I disable just those checkboxes?

Note: once a student has been checked you cannot uncheck that student (ie: remove the student from the class join table on the backend)




HelpProvider in checbox list specific item (C#)

I'm making an app which uses a checkbox list. Each item has to have a "description", so I decided to make it with a HelpProvider. But the problem is that when I make a loop that should fill all the checkboxes in checkbox list with a helprovider, Visual tells me that it is an object which cannot be converted into System.Windows.Forms.Control

Any ideas for a workaround?

for (int i = 0; i < CheckedListBox.Items.Count; i++)
{
     this.AdditionalInfos.SetShowHelp(CheckedListBox.Items[i], true);
     this.AdditionalInfos.SetHelpString(CheckedListBox.Items[i], "example description");
}




Kendo TreeList with checkboxes on ASPNET Mvc

I'm using Kendo (and I've almost never used it before) in an ASPNET Mvc application and I need to create a TreeList with checkboxes: checking a father should check all children and unchecking a child should uncheck the father (and the grandfather, and so on). The tree in itself works well: I've added a column with custom template and I'm using (successfully) the onClick event to get the value of the checkbox, but I can't figure out how to "bind" that value to the node of the tree (to reach every child and check it).

Here the code:

@(Html.Kendo().TreeList<TreeElem>()
  .Name("treelist")
  .Columns(col =>{                                                                
     col.Add().Field(f => f.NodeDescription).Title("TREE LIST");
     col.Add().Template("<input type='checkbox' data-bind='checked: checked' onClick='onCheck(event)'/>").Width(55);
   })
   .DataSource(source => source.Read(read => read.Action("GetData", "TreeController"))
   .Model(m => {                                                                                                
             m.Id(f => f.NodeId); 
             m.ParentId(f => f.ParentId);
             m.Field(f => f.NodeDescription);
       })
    )
)

In the javascript:

function onCheck(e) {
  console.log(e.target.checked); //print true/false according to the checkbox
  console.log($("#treelist").data('kendoTreeList').dataSource.data()); //print the complete node list 
  //Other stuffs
}

I would like to get the right node from data() (or view()) according to the checkbox selected. Every node has references to his children and father, so the recursive function should be easy after that. I've looked for and tried a lot of solutions but with almost no result, any idea? Thanks




Searchview and checkbox in recyclerview

I have a recyclerview with checkbox and searchview also whenever i am searching name and check the first view and then erase the searchview then bydefault it checked the first position view of recyclerview.please help me




How to Validate Checkbox in angular 5

i am trying to validate my checkbox in a form with different fields, but the problem i am getting is that

html code:

 <div class="form-group">
          <label class="login_label">Courses</label>
          <span style="color:#00bfff">*</span>
          <input [ngModelOptions]="{standalone: true}" [(ngModel)]="courses_mba" type="checkbox" class="" value="mba">Mba
          <input [ngModelOptions]="{standalone: true}" [(ngModel)]="courses_btech" type="checkbox" class="" value="btech">Btech
          <input [ngModelOptions]="{standalone: true}" [(ngModel)]="courses_mtech" type="checkbox" class="" value="mtech">Mtech
          </div>

Ts Code:

if (this.jobForm.invalid && (this.courses_mba === undefined || this.courses_btech === undefined || this.courses_mtech === undefined)) {
  this.snackBarService.requiredValue(' Please complete the form');
} else {
  this.job_courses = this.courses_mtech ? 'mtech' : '' + this.courses_btech ? 'btech' : '' + this.courses_mba ? 'mba' : '';
  this.snackBarService.requiredValue(' form Submitted Successfully');
  console.log('CArray', this.job_coursess);
  console.log('Course', this.job_courses);
  console.log('mba', this.courses_mba);
  console.log('mtech', this.courses_btech);
  console.log('btech', this.courses_mtech);

i am trying to display whose are checked should be display on console by i am not getting the proper output, even the checkbox are not selected the "job_courses" is showing the "btech" i tried to check by check mba and btech its giving me random value i.e sometime btech sometime mtech. What i am expecting is that what i checked should be display in console.




Xamarin.FormsCustom Renderer (Checkbox) size

I followed this article ...

https://alexdunn.org/2018/04/10/xamarin-tip-build-your-own-checkbox-in-xamarin-forms/

to add a checkbox control to Xamarin.forms. It works well, but I cannot figure out how to resize it.

Details: I have a layout with a rowspan=2 cell spanning two regular cell heights. I get a tiny checkbox sitting in the center of the rowspan, with lots of unused space around it, and users find it is hard to hit when tapping. Therefore I want it double its size according to rowspan=2.

Any idea how I can accomplish this?




lundi 25 juin 2018

get checkbox value datatables pagination

Help second page checkbox value get. i cant get value checkbox.jsfiidle link is here . help guys :)

$(document).ready(function () {
    var table = $('#example').DataTable({});

    // Handle click on "Select all" control
    $('#example-select-all').on('click', function () {
        // Check/uncheck all checkboxes in the table
        var rows = table.rows({ 'search': 'applied' }).nodes();
        $('input[type="checkbox"]', rows).prop('checked', this.checked);
    });
});

$("#gg").click(function () {
    $("input:checkbox[class=chk]:checked").each(function () {
        alert($(this).val());
    });
});

Visit : https://jsfiddle.net/07Lrpqm7/4089/




Getting ID of certain checkboxes and disabling them

I'm trying to get the ID of certain checkboxes and set the boxes to disabled based on conditions. However, I get this error on "Add:767 Uncaught TypeError: Cannot read property 'disabled' of null at HTMLInputElement.el.addEventListener.event (Add:767)". Why is it returning null? Am I not getting the element by ID?

This is the JS:

    var days = 0;
    const checkboxMonthElement = document.querySelectorAll('.checkboxMonth');
    const checkboxDofmElement = document.querySelectorAll('.checkboxDofM');


    var test123 = document.getElementById('#Schedule_DofMInfo_27__IsChecked');

    checkboxMonthElement.forEach(el => el.addEventListener('change', event => {

        days = 0;

        for (var i = 0; i < checkboxMonthElement.length; i++) {


            var NofD = parseInt($(checkboxMonthElement[i]).attr('data-test'));

            if (checkboxMonthElement[i].checked) {
                if (days < NofD)
                    days = NofD;
            }
        }
        console.log(days);

        if (days = 28) {
            console.log("Days is 28");
            console.log(test123);

           document.getElementById('#Schedule_DofMInfo_27__IsChecked').disabled === true;
        }





    }));

Here is the HTML:

   <li class="list-group-item" style="display:inline-block">
                    <div class="checkbox-inline" id="checkboxDofM">
                        <input data-val="true" data-val-number="The field DofMID must be a number." data-val-required="The DofMID field is required." id="Schedule_DofMInfo_26__DofMID" name="Schedule.DofMInfo[26].DofMID" type="hidden" value="26" />
                        <input class="checkboxDofM" data-val="true" data-val-required="The IsChecked field is required." id="Schedule_DofMInfo_26__IsChecked" name="Schedule.DofMInfo[26].IsChecked" type="checkbox" value="true" /><input name="Schedule.DofMInfo[26].IsChecked" type="hidden" value="false" />
                        <label for="Schedule_DofMInfo_26__IsChecked">27</label>
                    </div>
                </li>
                <li class="list-group-item" style="display:inline-block">
                    <div class="checkbox-inline" id="checkboxDofM">
                        <input data-val="true" data-val-number="The field DofMID must be a number." data-val-required="The DofMID field is required." id="Schedule_DofMInfo_27__DofMID" name="Schedule.DofMInfo[27].DofMID" type="hidden" value="27" />
                        <input class="checkboxDofM" data-val="true" data-val-required="The IsChecked field is required." **id="Schedule_DofMInfo_27__IsChecked"** name="Schedule.DofMInfo[27].IsChecked" type="checkbox" value="true" /><input name="Schedule.DofMInfo[27].IsChecked" type="hidden" value="false" />
                        <label for="Schedule_DofMInfo_27__IsChecked">28</label>
                    </div>
                </li>
                <li class="list-group-item" style="display:inline-block">
                    <div class="checkbox-inline" id="checkboxDofM">
                        <input data-val="true" data-val-number="The field DofMID must be a number." data-val-required="The DofMID field is required." id="Schedule_DofMInfo_28__DofMID" name="Schedule.DofMInfo[28].DofMID" type="hidden" value="28" />
                        <input class="checkboxDofM" data-val="true" data-val-required="The IsChecked field is required." id="Schedule_DofMInfo_28__IsChecked" name="Schedule.DofMInfo[28].IsChecked" type="checkbox" value="true" /><input name="Schedule.DofMInfo[28].IsChecked" type="hidden" value="false" />
                        <label for="Schedule_DofMInfo_28__IsChecked">29</label>
                    </div>
                </li>
                <li class="list-group-item" style="display:inline-block">
                    <div class="checkbox-inline" id="checkboxDofM">
                        <input data-val="true" data-val-number="The field DofMID must be a number." data-val-required="The DofMID field is required." id="Schedule_DofMInfo_29__DofMID" name="Schedule.DofMInfo[29].DofMID" type="hidden" value="29" />
                        <input class="checkboxDofM" data-val="true" data-val-required="The IsChecked field is required." id="Schedule_DofMInfo_29__IsChecked" name="Schedule.DofMInfo[29].IsChecked" type="checkbox" value="true" /><input name="Schedule.DofMInfo[29].IsChecked" type="hidden" value="false" />
                        <label for="Schedule_DofMInfo_29__IsChecked">30</label>
                    </div>
                </li>
                <li class="list-group-item" style="display:inline-block">
                    <div class="checkbox-inline" id="checkboxDofM">
                        <input data-val="true" data-val-number="The field DofMID must be a number." data-val-required="The DofMID field is required." id="Schedule_DofMInfo_30__DofMID" name="Schedule.DofMInfo[30].DofMID" type="hidden" value="30" />
                        <input class="checkboxDofM" data-val="true" data-val-required="The IsChecked field is required." id="Schedule_DofMInfo_30__IsChecked" name="Schedule.DofMInfo[30].IsChecked" type="checkbox" value="true" /><input name="Schedule.DofMInfo[30].IsChecked" type="hidden" value="false" />
                        <label for="Schedule_DofMInfo_30__IsChecked">31</label>
                    </div>
                </li>
        </ul>
        <div class="checkbox-inline">
            <input id="checkAllDofm" name="checkAll" onclick="toggleDofM(this);" type="checkbox" value="true" /><input name="checkAll" type="hidden" value="false" />
            <label for="Select_All">Select All</label>
        </div>
    </div>
</center>




Checking if checkbox is checked or not Javascript

I am trying to determine in code whether a checkbox is checked or not, looking at this: w3 Schools Checkbox checked source, I changed the code around a bit to look like this:

           if(document.getElementById("option_seo").checked == true)
           {
            var seo = parseInt(document.getElementById("option_seo").value;
           }

and that does not work. I have seen solutions around overflow that deal with for loop statements and I don't believe my situation is needing a for statement, if anyone is able to assist me in this, that would be great! Thanks!




select multiple columns by checkboxGroupInput in R shiny

I have a question about how to select multiple columns in my dataset by checkboxGroupInput in R shiny.

Now my dataset have a column like this: (the pattern is stateName/number/number)

IndividualName

SA/111111/222222

VIC/33333/444444

NSW/55555/666666

QLD/777777/888888

.....

and I have a select box that works well. I use grepl to extract state name and I can choose individual state successfully.

UI:

        selectInput("select_state", h3("Select State"),
                choices = list("All States"="SA|VIC|NSW|QLD|WA|TAS|NT|ACT|CTH","South Australia"="SA",
                               "Victoria"="VIC","New South Wales"="NSW","Queensland"="QLD",
                               "Western Australia"="WA","Northern Territory"="NT","Tasmania"="TAS",
                               "Australian Capital Territory"="ACT","Commonwealth"="CTH")),

Server:

entities_state <- entities[ with(entities, grepl(input$select_state, c(entities$IndividualName))), ]

Now I want to change the select box to checkbox group, I know to use checkbox group, we can write

entities_state <-filter(entities, IndividualName %in% input$select_state)

but I still need extract stateName keyword from the "IndividualName" column. I don't know how to combine grepl, filter, and %n% to make the checkbox group work.

I hope I express my problem clearly. If not, please let me know.




Bootstrap 4 custom-checkbox same format as text input?

I have Bootrap 4 text input like this

<div class="col-2 form-group">
    <label for="follow">Följande</label>
    <input type="text" class="form-control" id="follow" name="Follow" placeholder="" value="" required>
    <div class="invalid-feedback">
        Vänligen fyll i Följande.
    </div>
</div>

And I want the checkbox label same vertical level as the text input and the check same vertical level and size as the text input. I have tried to swap the input and label code but nothing is working.

Checkbox code with custom checkbox.

<div class="custom-control custom-checkbox">
  <input type="checkbox" class="custom-control-input" id="customCheck1">
  <label class="custom-control-label" for="customCheck1">Check</label>
</div>

I have it like this

But want it like this




Post checkbox id to php via AJAX

I want to create a network graph using checkboxes. If I select 1 or more checkboxes then I click on the button, I want to draw network graph from the selected checkboxes. It's actually works, but if I select more than 1, it just prints 1 node, but if I select just 1, it's working perfectly. How can I solve this problem?

index.php

<td align="center"><input id="'.$row["id2"].'" class="checkboxes" type="checkbox" value="'.$row["id2"].'"</td>

<script>
            $(document).ready(function(){
                $('.relations').click(function(e){  
                    e.preventDefault();
                    $("#dataModal3").modal("hide");

                    // Checkboxes
                    var insert=[];
                    $('.checkboxes').each(function(){
                        if($(this).is(":checked")){
                            insert.push($(this).val());
                        }
                    });
                    insert=insert.toString();

                    var data_id = $(this).attr("id");  
                    $.ajax({  
                        url:"nodes.php",
                        method:"post",
                        dataType: "json",
                        data:{data_id:data_id,insert:insert},  
                        success:function(data){  
                            $('#moreInfo').html(data);  
                            $('#dataModal').modal("show");  
                            var nodeDatas = new vis.DataSet();
                            nodeDatas = data;

                            $.ajax({
                                method:"post",
                                dataType: "json",
                                url: "edges.php",
                                data:{data_id:data_id},
                                success: function(data){
                                    var edgeDatas = new vis.DataSet();
                                    edgeDatas = data;
                                    var myDiv = document.getElementById("moreInfo");

                                    data={
                                        nodes: nodeDatas,
                                        edges: edgeDatas
                                    };

                                    var options = {

                                    };

                                    var network = new vis.Network(myDiv, data, options);
                                }
                            });
                        }  
                    }); 
                });
            });
        </script>

nodes.php

if(isset($_POST["insert"])){

            $sql2=$conn->prepare("SELECT id, data
                FROM table1

                WHERE id=?
                GROUP BY id");

            $sql2 -> bind_param('i', $_POST['insert']);
            $sql2 -> execute();
            $result2 = $sql2 -> get_result();
            $sql2 -> close();

            while($row = mysqli_fetch_assoc($result2)){
                $id2 = $row['id'];
                $data = $row['data'];


                $arr[] = array("id" => $id2,
                    "label" => $data);
            }

        }




Javascript Checkbox Display Error

I am using javascript to check if a checkbox is ticked or not. There are 3 checkboxes and only one can be selected at a time. I am using the following code which works fine, when I uncheck a box and check another the div displays correctly but if I select one then select another e.g have selected checkbox1 and select checkbox2 the "testing" div still appears and the "video" div does not appear. I am guessing this is just something really simple but I can't work it out

<script>
function checkFunction() {

    var checkBox = document.getElementById("myCheck1");
    var text = document.getElementById("testing");

     var checkBox2 = document.getElementById("myCheck2");
    var text2 = document.getElementById("video");
     var checkBox3 = document.getElementById("myCheck3");
    var text3 = document.getElementById("html");
    if (checkBox.checked == true){
        text.style.display = "block";
        text2.style.display = "none";
        text3.style.display = "none";
    }  else {
        text.style.display = "none";
        if (checkBox2.checked == true){
            text2.style.display = "block";
            text.style.display = "none";
            text3.style.display = "none";
            }  else {
            text2.style.display = "none";
            if (checkBox3.checked == true){
                text3.style.display = "block";
                text2.style.display = "none";
                text.style.display = "none";
            }  else {
                text3.style.display = "none";
                text.style.display = "none";
                text2.style.display = "none";
            }
        }
    }
}
</script> 
</script> 
    <script type="text/javascript">
    $('.check').on('change', function() {
        $('.check').not(this).prop('checked', false)
    });
  </script>




dimanche 24 juin 2018

Jquery how to check own child element only

I want to implement jquery each function in here. Menu contains submenu, if submenu has not been checked when it's parent menu is being checked, then it have to be stopped to submit. But here sports and vehicle menu consider each other submenu as common submenu, It cann't stop if another's submenu has checked I tried each function, so jquery condition would be applied only own child element, but it doesn't work.

$(document).on('submit', '#form', function(e) {
  e.preventDefault();
  if ($("[name='menu[]']:checked").length == 0) {
    alert('Missing menu');
    return false;
  }
  if ($("[name='menu[]']:checked").val() == 2 && $("[name^='submenu']:checked").length == 0) {
    alert('Missing submenu');
    return false;
  }
  if ($("[name='menu[]']:checked").val() == 12 && $("[name^='submenu']:checked").length == 0) {
    alert('Missing submenu');
    return false;
  } else {
    alert('Success');
  }
});
ul li {
  list-style: none;
  float: left;
}

ul li ul li {
  float: none;
}

.col100 {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
  <ul>
    <li><input type="checkbox" name="menu[]" value="2">Vehicle
      <ul>
        <li><input type="checkbox" name="submenu[2][1]">Bike</li>
        <li><input type="checkbox" name="submenu[2][2]">Car</li>
        <li><input type="checkbox" name="submenu[2][3]">Cycle</li>
      </ul>
    </li>
    <li><input type="checkbox" name="menu[]" value="12">Sport
      <ul>
        <li><input type="checkbox" name="submenu[12][1]">Basketball</li>
        <li><input type="checkbox" name="submenu[12][2]">Volleyball</li>
        <li><input type="checkbox" name="submenu[12][3]">Football</li>
      </ul>
    </li>
  </ul>
  <input type="submit" name="submit" value="submit" class="col100">
</form>



Vue js checkbox custom component

i'm having problems with checkbox in vue.js component. My idea is to update parent model on child event(change).

<parent-component>
     <checkbox-component name="This is name"
                        :id="'This is Id'"
                        :val="'test'"
                        v-model="details"
                >
     <checkbox-component name="This is name 2"
                        :id="'This is Id 2'"
                        :val="'test2'"
                        v-model="details"
                >
     </checkbox-component>
</parent-component>

Here is component code:

    <template>
    <div>
        <input type="checkbox"
               :name="name"
               :id="id"
               :value="val"
               v-on:change="update($event)"
               autocomplete="off"
        />
        <div class="btn-group">
            <label :for="id" class="btn btn-default btn-sm">
                <span class="glyphicon glyphicon-ok"></span>
                <span> </span>
            </label>
            <label :for="id"
                   class="btn btn-default active btn-sm">
                
            </label>
        </div>
    </div>
</template>
<script>
    export default {
        model: {
            event: 'change'
        },
        props: {
            id: {
                required: true,
                type: String
            },
            name: {
                required: true,
                type: String
            },
            val: {
                required: true,
                type: String
            },

        },

        methods: {

            update(event){

                this.$emit('change',event.target.value);
            }

        },
    }
</script>

I would like to store checkbox values in details array, and to update it same as in https://vuejs.org/v2/guide/forms.html#Checkbox

What is happening now is that details[] is becoming string details with value of selected checkbox.

Is there some clean solution for this, or i need to write method to check if value is in array and slice/push it ?




I have to double click checkbox to change it's status in Marionette ;/

I have a checkbox with class js-map-source in my HBS template. I am listening clicks on this checkbox in Marionette view. This part is working correctly - when I click on checkbox I am able to console.log checkbox status.

Code:

module.exports = Marionette.ItemView.extend({
  # something else....

  ui: {
    mapSource: '.js-map-source'
    # something else...
  },

  events: {
    'click @ui.mapSource': 'mapSourceChanged'
    # something else...
  }

  # something else...

  mapSourceChanged: function (event) {
    var switchStatus = $(this.ui.mapSource).is(":checked");
    console.log(`TypeOf: ${typeof switchStatus}; value: ${switchStatus}`);
  },
}

So let's click few times. Following logs appers in console:

TypeOf: boolean; value: true
TypeOf: boolean; value: false
TypeOf: boolean; value: true
TypeOf: boolean; value: false
TypeOf: boolean; value: true
TypeOf: boolean; value: false
TypeOf: boolean; value: true
TypeOf: boolean; value: false
TypeOf: boolean; value: true
TypeOf: boolean; value: false`

That was expected behaviour.

The problem occurs when I am trying to save this checkbox value (true/false) in my model. Let's add this.model.set('source', switchStatus) to the function mapSourceChanged.

Now I have to double click checkbox to mark is as checked (visually). But still, I can uncheck checkbox with one click.

Code:

module.exports = Marionette.ItemView.extend({
  # something else....

  ui: {
    mapSource: '.js-map-source'
    # something else...
  },

  events: {
    'click @ui.mapSource': 'mapSourceChanged'
    # something else...
  }

  # something else...

  mapSourceChanged: function (event) {
    var switchStatus = $(this.ui.mapSource).is(":checked");
    console.log(`TypeOf: ${typeof switchStatus}; value: ${switchStatus}`);
    this.model.set('source', switchStatus);
  },
}

Logs:

2TypeOf: boolean; value: true
TypeOf: boolean; value: false
2TypeOf: boolean; value: true
TypeOf: boolean; value: false
2TypeOf: boolean; value: true
TypeOf: boolean; value: false
2TypeOf: boolean; value: true
TypeOf: boolean; value: false
2TypeOf: boolean; value: true

This 2 on the beginning of the line means that I get the same log again.

What is the reason for this behaviour? How to fix it?




vendredi 22 juin 2018

Trigger checkbox change event with plain javascript (NOT jQuery)

I'm building a multiple select with ES6. It's all up and functional (moving trough items, clicking them, highlighting, whatever you want) but the only problem is handling those checkboxes. Whenever an item is highlighted and enter is pressed I must catch the event, verify the number of checked items and update dropdown's title.

The methods I found so far are based on using document.createEvent() and fireEvent(), but they both are deprecated (and yes, I can't figgure out how to solve it with CustomEvent).

I've been trying to find an answer for 3 days now, trust me when I say I tried my best.

checkbox.checked = true
checkbox.checked = false

only change checkbox value but won't trigger any event




Tkinter: checkbox list not responsive

I am trying to create a list of checkbox with a loop. I have modified the implementation of someone else's code which uses the same concept and should have the same function as what I want. When I try to print the state of each checkbox, none of them are updated to 1. They all stay at 0 even if I click them. Here is my code, the test() function doesn't behave as I expect it to. Thanks in advanced for the help

import tkinter
import tkinter.filedialog
import os

# --- functions ---

def browse():

    filez = tkinter.filedialog.askdirectory(parent=window, title='Choose a file')

    ent1.insert(20, filez)

    dirs = os.listdir(filez)

    # remove previous IntVars
    intvar_dict.clear()

    # remove previous Checkboxes
    for cb in checkbutton_list:
        cb.destroy()
    checkbutton_list.clear() 


    for filename in dirs:
        # create IntVar for filename and keep in dictionary
        var = tkinter.IntVar()

        # create Checkbutton for filename and keep on list
        c = tkinter.Checkbutton(window, text=filename, variable=var)
        c.pack()
        intvar_dict[filename] = var
        checkbutton_list.append(c)

def test():


    for key, value in intvar_dict.items():


        if value.get() > 0:
            print("HIIIIII")
        print('selected:', key)
        #print (value.get())

# --- main ---

# to keep all IntVars for all filenames
intvar_dict = {}
 # to keep all Checkbuttons for all filenames
checkbutton_list = []

window = tkinter.Tk()

lbl = tkinter.Label(window, text="Path")
lbl.pack()

ent1 = tkinter.Entry(window)
ent1.pack()

btn1 = tkinter.Button(window, text="Select Path", command=browse)
btn1.pack()

btn1 = tkinter.Button(window, text="Test Checkboxes", command=test)
btn1.pack()

window.mainloop()




Detect Shift key + click event on iCheck checkbox

My web page uses iCheck checkboxes. I am trying to get event when Shift key is pressed along with clicking on checkboxes. but no where in the documentation, iCheck gives that notification like normal document.click(function()) gives.

I am using

$('input[name=selectinp]').on('ifChanged', function(event){ 
...
});

Here, event.shiftkey is undefined. Please help.




How to make checkbox value checked from an array

I am using ion-checkbox

<ion-list *ngIf = "heirList.length > 0">
  <ion-item *ngFor = "let each of heirList">
    <ion-label>
      <h5> </h5>
      <h5 clear item-end class="text-blue badge-alert"> #102</h5>
    </ion-label>
    <ion-checkbox  class="selectlist" (ionChange) = "addHeir(each)"></ion-checkbox>
  </ion-item>
</ion-list>

addHeir(each) is checking if the element is present in another array if its present it removes it else it adds that element in that array, everything is working fine till now but if I come back to that page it doesn't show the checkbox checked.

addHeir(value) function is below :

addHeir(value) {
    let index = tempArray.indexOf(value);
    if (index != -1) {
      tempArray.splice(index, 1);
    }
    else {
      tempArray.push(value);
    }
    console.log(tempArray.value);
  }




jeudi 21 juin 2018

Post checkbox values then encode to json

I want to create network graph with checkboxes. If I click a data's button, it shows where this data is connected to. If I select 1 or more, I want to print the original data node (it's working), and the selected nodes. My idea is to post the checkbox, the button and the td to that PHP file where I encode it to JSON, but it's not working. Now if I click the button, the modal disappear.

How can I post the checkbox and the td values to another PHP file to encode it to JSON?

Checkbox

$output .='<form name="relationCheck" action="nodes.php" method="post">';

            while($row=$result->fetch_assoc()){ 

                $output .='

                <tr>  
                    <td align="center"><input name="id[]" class="checkboxes" type="checkbox" value="'.$row["id2"].'"</td>
                    <td>'.$row["data"].'</td>  
                </tr>  
            ';
while($row = $result3->fetch_assoc()){
            $output .= '<input type="button" name="submit" id="'.$row["data_id"].'" value="view" class="btn btn-success relations">';
            }
            $output .= '</form>';

nodes.php

$id2=$_POST['id'];

        if(isset($id2)){

            $sql2=$conn->prepare("SELECT id, data
                FROM table1
                WHERE id=?
                GROUP BY id");

            $sql2 -> bind_param('i', $id2);
            $sql2 -> execute();
            $result2 = $sql2 -> get_result();
            $sql2 -> close();

            while($row = mysqli_fetch_assoc($result2)){
                $id2 = $row['id'];
                $data = $row['data'];


                $arr[] = array("id" => $id2,
                    "label" => $data);
            } 


        echo json_encode($arr);




Unable to get Checked CheckBox values in Google sheet using google apps script

I am fairly new to google apps script.

I have made an HTML Form, whose values are being posted to a Google Sheet.

All is working fine with text boxes.

When I used a CheckBox, the values being represented in the sheet is showing undefined if a check box is unchecked.

I don't want that to happen.

Here is the code i have used.

index.html

<!DOCTYPE html> <html>   <head>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <script>
      // Prevent forms from submitting.

      function preventFormSubmit() {
        var forms = document.querySelectorAll('form');
        for (var i = 0; i < forms.length; i++) {
          forms[i].addEventListener('submit', function(event) {
            event.preventDefault();
          });
        }
      }
      window.addEventListener('load', preventFormSubmit);

      function handleFormSubmit(formObject) {
        google.script.run.withSuccessHandler(updateUrl).processForm(formObject);
      }
      function updateUrl(url) {
        var div = document.getElementById('output');
        div.innerHTML = url;
      }


    </script>   </head>   <body>   <center>   <table>
    <caption>SPAC KYC FORM</caption>
    <form id="myForm" onsubmit="handleFormSubmit(this)">   
      <tr><td>Form Filled By: *</td><td><input type="checkbox" name="id0" value="Dealer"></td></tr>
      <tr><td>Form Filled By: *</td><td><input type="checkbox" name="id1" value="Trader"></td></tr>
      <tr><td> <input type="submit" value="Submit"></td></tr>

    </form>
    </table>
    <div id="output"></div>    </center>
       </body> </html>

Code.gs

    function doGet() {
  return HtmlService.createHtmlOutputFromFile('index');
}
function processForm(formObject) {

     var form_filled_by = formObject.id0;
     var form_filled_by2 = formObject.id1;


  //Insert in Spreadsheet
  var SpreadsheetKey = "1D6gMFBiSJqZvPNJvo-HMG52ZIj4NUPR8wiNGCg91tAk";

  var sheet = SpreadsheetApp.openById(SpreadsheetKey).getActiveSheet();  

  var lastrow = sheet.getLastRow();
  var lastcolumn = sheet.getLastColumn();



  var targetrange0 = sheet.getRange(lastrow+1,1,1,1).setValues([[form_filled_by + ", " +form_filled_by2]]);

  var htmlbody1 =  "<html><body>Form Filled with Value:" + form_filled_by + ", " + form_filled_by2 + "</body></html>"; 

  //Display on Webpage
  return HtmlService.createHtmlOutput(htmlbody1).getContent();
  //return alert(htmlbody1);
}

Here is a look at the gsheet

I need that undefined is not displayed in sheet.

Please Help.

I got a little help from this link How to get values of all Checked checkboxes in Google App Script

but I am unable to apply it.




Bootstrap contact_me.php validate checkbox is checked?

I am trying to add a checkbox to my simple contact form. I want this to be validated so it checks before being able to send the form. I would really appreciate some help.

FORM:

<form id="contactForm" name="sentMessage" novalidate="">
<div class="control-group form-group">
<div class="controls"><label>Navn:</label> <input id="name" class="form-control" required="" type="text" data-validation-required-message="Skriv inn ditt navn." />
<p class="help-block"> </p>
</div>
</div>
<div class="control-group form-group">
<div class="controls"><label>Telefonnummer:</label> <input id="phone" class="form-control" required="" type="tel" data-validation-required-message="Skriv inn et telefonnummer." />
<div class="help-block"> </div>
</div>
</div>
<div class="control-group form-group">
<div class="controls"><label>E-post:</label> <input id="email" class="form-control" required="" type="email" data-validation-required-message="Skriv inn en e-postadresse." />
<div class="help-block"> </div>
</div>
</div>
<div class="control-group form-group">
<div class="controls"><label>Melding:</label> <textarea id="message" class="form-control" style="resize: none;" cols="100" maxlength="999" required="" rows="10" data-validation-required-message="Skriv en melding"></textarea>
<div class="help-block"> </div>
</div>
</div>


CHECKBOX IS WANTED HERE


<div id="success"> </div>
<!-- For success/fail messages --> <button id="sendMessageButton" class="btn btn-success" type="submit">Send oss melding</button></form>

contact_me.js:

$(function() {

  $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
      // additional error messages or events
    },
    submitSuccess: function($form, event) {
      event.preventDefault(); // prevent default submit behaviour
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    event: 'Kontaktskjema',
    formId: 'contactForm'
  });
      // get values from FORM
      var name = $("input#name").val();
      var email = $("input#email").val();
      var phone = $("input#phone").val();
      var message = $("textarea#message").val();
      var firstName = name; // For Success/Failure Message
      // Check for white space in name for Success/Fail message
      if (firstName.indexOf(' ') >= 0) {
        firstName = name.split(' ').slice(0, -1).join(' ');
      }
      $this = $("#sendMessageButton");
      $this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
      $.ajax({
        url: "/mail/contact_me.php",
        type: "POST",
        data: {
          name: name,
          phone: phone,
          email: email,
          message: message
        },
        cache: false,
        success: function() {
          // Success message
          $('#success').html("<div class='alert alert-success'>");
          $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
            .append("</button>");
          $('#success > .alert-success')
            .append("<strong>Takk, meldingen er sendt. </strong>");
          $('#success > .alert-success')
            .append('</div>');
          //clear all fields
          $('#contactForm').trigger("reset");
        },
        error: function() {
          // Fail message
          $('#success').html("<div class='alert alert-danger'>");
          $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
            .append("</button>");
          $('#success > .alert-danger').append($("<strong>").text("Beklager " + firstName + ", noe gikk feil med sendingen. Prøv igjen senere!"));
          $('#success > .alert-danger').append('</div>');
          //clear all fields
          $('#contactForm').trigger("reset");
        },
        complete: function() {
          setTimeout(function() {
            $this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
          }, 1000);
        }
      });
    },
    filter: function() {
      return $(this).is(":visible");
    },
  });

  $("a[data-toggle=\"tab\"]").click(function(e) {
    e.preventDefault();
    $(this).tab("show");
  });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
  $('#success').html('');
});

contact_me.php:

<?php
// Check for empty fields
if(empty($_POST['name'])      ||
   empty($_POST['email'])     ||
   empty($_POST['phone'])     ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
   echo "No arguments Provided!";
   return false;
   }

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$to = 'email@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Kontaktskjema domain.com:  $name";
$email_body = "Du har mottatt en melding fra kontaktskjemaet paa nettsiden domain.com.\n\n"."Her er meldingen:\n\nNavn: $name\n\nE-post: $email_address\n\nTelefon: $phone\n\nMelding:\n$message";
$headers = "From: noreply@domain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";   
mail($to,$email_subject,$email_body,$headers);
return true;         
?>

The form is working fine now, but whatever I try to validate, if a checkbox is checked it stops working. I have searched and tried all the solutions I could find.




How to add data- attributes in Checkbox component via inputProps

I use Fabric components written in React + Typescript and when using Checkbox component I can add custom attributes such as data-id and so on - this is written also on documentation: https://developer.microsoft.com/en-us/fabric#/components/checkbox

Whats the problem ? I do not know how to add one by passing it to inputProps.

Interface of React HTMLAttribute for field data require string value.

From what I see there interface of React's HTMLAttribute is generic one and Checkbox component passes this interfaces there: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/global.d.ts - They are empty.

Does somebody know how to implement the data- attributes there ?

Thanks. Cheers!




Swift Cocoa - Selected checkbox cell in NSTableview

I'm learning to create a simple program in Cocoa swift. What I'm trying to do here is to create a tableview with 2 columns. One for CheckBox and one for TextView.

Simple Cocoa app

But I cannot change the checkbox state when click on the checkbox. What I need is when I click a checkbox, it's select that row on the tableview. Are there any event for the checkbox so I can check it?

Here is my code

import Cocoa

let Mydirectory: [String] = ["John", "Davis", "Mark", "Sarah", "Kim", 
"Hanna"]

class ViewController: NSViewController, NSTableViewDataSource, 
NSTableViewDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func awakeFromNib() {

}

@IBOutlet weak var table: NSTableView!

override var representedObject: Any? {
    didSet {
    // Update the view, if already loaded.
    }
}

func numberOfRows(in tableView: NSTableView) -> Int {
    return Mydirectory.count
}

func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {

    return Mydirectory[row]
}
}




Two checkboxes with sharing state in MS Word without VBA

Is there any way to duplicate checkbox with sharing state? So click on one make them both checked




PrimeNG checkbox not getting checked by default

I have an angular project in which I am using a PrimeNG checkbox component but there is an issue when I am trying to set the checkbox's default value to checked. I even tried binding [checked] property but I guess it is not known to p-checkbox.

HTML file

<p-checkbox name="checkboxName" [(ngModel)]="checked" 
binary="true" label="Perform Notifications"></p-checkbox>



Component file

export class XYZ{
checked: boolean = true;
}

When that gets loaded, I can see value of checked variable as 'true' below in HTML page but the checkbox is blank or unchecked.




mercredi 20 juin 2018

HTML checkbox "checked" attribute does not let unchecking on the page

When I am trying to use html checkbox "checked" property, the checkbox is initially checked on the page. However, I cannot uncheck it at all during the session. Here is the code I am talking about:

<input type="checkbox" id="coding" name="interest" value="coding" checked="true" />

When I set the "checked" property to "false", it is allowing changes (able to be checked and unchecked). Can anyone explain the reasons for that?




Javascript won't execute second if statement

For some reason, the function only runs the first if statement. When I flipped the two sections the first one ran and the second one did not. The first set works as intended... 1. Adds image if checkbox is checked and the destination is empty 2. Does nothing if checkbox is checked and the destination has the image already 3. Removes the image if the checkbox is unchecked.

<input type="checkbox" id="mGT">
<input type="checkbox" id="ICE">
<div class="box" id="disp_mGT"></div>
<div class="box" id="disp_ICE"></div>
<button id="show_button">Show System</button>

<script>
var show_button = document.getElementById('show_button');
var show = function() {
//// AC Components
// Get trues and falses
var mGT_ch = document.getElementById('mGT').checked;
var ICE_ch = document.getElementById('ICE').checked;

// ICE Display/Not-Display
var disp_ICE = document.getElementById("disp_ICE");
var disp_ICE_len = disp_ICE.childNodes.length
if (ICE_ch && disp_ICE_len == 0) {
    var ICE_img = document.createElement('img')
    ICE_img.src="http://localhost/Graphics/ICE.png";
    disp_ICE.appendChild(ICE_img);
} else if (ICE_ch && disp_ICE_len == 1) {
} else {    
    disp_ICE.removeChild(disp_ICE.childNodes[0]);
}

// Micro Turbine Display/Not-Display
var disp_mGT = document.getElementById("disp_mGT");
var disp_mGT_len = disp_mGT.childNodes.length
if (mGT_ch && disp_mGT_len == 0) {
    var mGT_img = document.createElement('img')
    mGT_img.src="http://localhost/Graphics/mGT.png";
} else if (mGT_ch && disp_mGT_len == 1) {
} else {    
    disp_mGT.removeChild(disp_mGT.childNodes[0]);
}
}
show_button.addEventListener("click",show);
</script>
</body>




Enlarge the radiobutton and checkbox bullet binding with Text size

The radio button and checkbox will be adding to window dynamically which based from how many data will be on database.

I have try some approach but cannot get what I need. Below are the code that will be perform to add either radio button or checkbox:-

private void ScreenSubList_Loaded(object sender, RoutedEventArgs e)
{
    try
    {
        strSubList LastGroupName = strSubList.Empty;
        foreach (var SubList in ProductSubList)
        {
            StackPanel StackGroup = new StackPanel() { Orientation = Orientation.Vertical };
            if (SubList.GroupName != LastGroupName)
            {
                Label LabelGroupName = new Label() { Content = SubList.GroupName.ToUpper() };
                ScaleTransform ElementScaleTransform = new ScaleTransform(6, 6);
                LabelGroupName.RenderTransform = ElementScaleTransform;
                StackGroup.Children.Add(LabelGroupName);
                LastGroupName = SubList.GroupName;
            }

            if (SubList.GroupType == 0)
            {
                RadioButton rb = new RadioButton();
                if (SubList.SubListItem != null)
                {
                    StackPanel StackItem = new StackPanel() { Orientation = Orientation.Horizontal };
                    foreach (var SubListitem in SubList.SubListItem)
                    {
                        rb.Tag = SubListitem.ItemID;
                        rb.Name = "SubList" + SubListitem.ItemID;
                        rb.Content = SubListitem.ItemName;
                        rb.HorizontalContentAlignment = HorizontalAlignment.Left;
                        rb.VerticalContentAlignment = VerticalAlignment.Center;
                        rb.GroupName = SubList.GroupName;
                        ScaleTransform ElementScaleTransform = new ScaleTransform(5, 5);
                        rb.RenderTransform = ElementScaleTransform;
                        StackGroup.Children.Add(rb);
                    }
                }
            }
            else if (SubList.GroupType == 1)
            {
                CheckBox cbx = new CheckBox();
                if (SubList.SubListItem != null)
                {
                    StackPanel StackItem = new StackPanel() { Orientation = Orientation.Horizontal };
                    foreach (var SubListitem in SubList.SubListItem)
                    {
                        cbx.Tag = SubListitem.ItemID;
                        cbx.Name = "SubList" + SubListitem.ItemID;
                        cbx.Content = SubListitem.ItemName;
                        cbx.HorizontalContentAlignment = HorizontalAlignment.Left;
                        cbx.VerticalContentAlignment = VerticalAlignment.Center;
                        ScaleTransform ElementScaleTransform = new ScaleTransform(5, 5);
                        cbx.RenderTransform = ElementScaleTransform;
                        StackGroup.Children.Add(cbx);
                    }
                }
            }
            ScreenSubListredient.StackSubList.Children.Add(StackGroup);
        }
    }
    catch (Exception ex)
    {
        App.LogEvents($"Exception on ScreenSubList_Loaded. Message-{ex.Message}. Stack Trace-{ex.StackTrace}", System.Diagnostics.EventLogEntryType.Error);
    }
}

I also play around with Blend to see the outcome from what I have test. Some of the test are:- 1. ScaleTransform the radiobutton and checkbox before adding to stackpanel 2. Group default radiobutton and checkbox into view.

Problem on the testing:

  1. ScaleTransform cannot stack to stackpanel accordingly
  2. Viewbox is having different size depend on the text length. If radiobutton or checkbox got lesser text, it will going big to stretch inside stackpanel. Manually adjusting the width and height make the viewbox and content look distort and will be a lot of work to calculate the Width and Height that will view the text at same size.

Below are the image sample as the output: Microsoft Blend Designer Visual

  • On most left, I just change the text size, text bigger but bullet options still tiny.

  • On middle, the options using Viewbox. All font is at default size Segoe UI 9pt

  • On most right, the usage of ScaleTransform. It was likely the middle pointer is stack vertically on panel. And it's unsure how to control base from latest size of the radiobutton and checkbox since on Height & Width properties, it show the default size before Transform.

What I need is actually a radio button and check box that have it's bullet follow the size of the text. I've go through internet for this for a weeks but not find any solutions to my situations.




Can't bind checkbox in partial view to the main model (MVC)

I've been running into to issue and I've been searching for an answer but nothing helped.

I have a Model:

public class Filters
{
    public bool Filter1 { get; set; }
    public bool Filter2 { get; set; }
    public bool Filter3 { get; set; }
    etc...
}

I have a partial view with multiple checkboxes and tried multiple things:

<input id="Filter1" name="Filter1" type="checkbox" value="true">
<input type="hidden" value="false" name="Filter1" />

and

@Html.CheckBoxFor(model => model.Filter1)

Then I have a main model:

public class Dashboard
{
    ...
    public Filters FiltersDashboard { get; set; }
}

And somewhere in the main view I insert the partial view like this:

@Html.EditorFor(model => model.FiltersDashboard, "Filters")

In a jquery, I execute an alert when the checkbox is clicked and shows the value of the checkbox. This value remains unchanged.

<script>
    $("#Filter1").click(function () {
        alert(" @Model.FiltersDashboard.Filter1 ")
    });
</script>

This tells me that something isn't correctly bound but I have no clue what I'm doing wrong.

Also, the reason I'm not using a checkboxlist is because I need to execute a different query for each filter so I need specific names and bindings for them.




Checkboxes when un checked and saved then uncheck is not saved in form in rails application

i have two checkboxes in my form(ruby on rails application) like below.

When i check these checkboxes and save then the checkboxes are getting checked and saved(till this its working fine).

after that when we uncheck and save these checkboxes, then these uncheck changes are not getting saved.(still showing checked.)

these are working in my local rails development environment. but the same code is not working in the server.

below is my code

<%= form_for @user, :url => url_for(:controller => 'user_controller', :action => 'investor_create_or_update'),html: { class: 'migrate-form' }, remote: true do |f| %>

<%= f.check_box :are_you_a_owner, class: "", placeholder: ""%><label>Are you a Business owner or Senior Manager?

<% end %>




mardi 19 juin 2018

JavaScript Function to validate checkbox

I'm trying to not allow both checkboxes to be checked at the same time. Here is my vanilla JS. I have the function already validating to return true when one is checked and false when neither are checked. Radio boxes are not an option.

 function valForm()
{
var both = document.getElementById("cEmail1" & "cPhone1");
for (var i = 1; i <= 2; i++)
{
    if (document.getElementById("cEmail1").checked)
    {
        return true;
    }
    else if (document.getElementById("cPhone1").checked)
    {
        return true;
    }
    else if (both.checked)
    {
        return false;
    }
    else
    { return false; }
}
}

here is my html

<form action="http://severien.com/grit/formecho.php" method="post" 
name="contactUsForm" onsubmit="return valForm()">


<span class="box3"><label for="cEmail" class="l5" >Contact me by email</label>
<input class="check1" id="cEmail1" type="checkbox" name="contactbyemail"  /></span>
<span class="box4"><label for="cPhone" class="l6">Contact me by phone</label>
<input class="check2" id="cPhone1" type="checkbox" name="contactbyphone"  /></span> <br />
<div class="formSubmit"><input type="submit" value="Submit" /></div> 
</form>
</div>




How can I draw network graph using checkboxes?

I have a table with MySQL datas. Each row has a button. If I click one of the button, a Bootstrap modal appears. This modal shows where this datas connected to. These have checkboxes: modal

If I select 1 or more then I click on the button, I want to show only the Data1 node and the selected nodes. For example I select data2 and data3 then it show the data1 node connect to the data2 and data3 nodes. How can I do this?

My network graph is working, because if I add it to the button that show the current data's relations, it draws the graph correctly.

Checkboxes

while($row=$result->fetch_assoc()){ 

                $output .='

                <tr>  
                    <td align="center"><input name="case" class="checkboxes" type="checkbox" value="'.$row["data2"].'"</td>
                    <td>'.$row["data2"].'</td>  
                    <td style="display: none;">'.$row["conn"].'</td> 
                </tr>  
            ';

            }

Javascript (network graph)

$(document).ready(function(){
                $('#checkBtn2').click(function(e){  
                    e.preventDefault();
                    var data_id = $(this).attr("id");  
                    $.ajax({  
                        url:"nodes.php",
                        method:"post",
                        dataType: "json",
                        data:{data_id:data_id},  
                        success:function(data){  
                            $('#moreInfo').html(data);  
                            $('#dataModal').modal("show");  
                            var nodeDatas = new vis.DataSet();
                            nodeDatas = data;

                            $.ajax({
                                method:"post",
                                dataType: "json",
                                url: "edges.php",
                                data:{data_id:data_id},
                                success: function(data){
                                    var edgeDatas = new vis.DataSet();
                                    edgeDatas = data;
                                    var myDiv = document.getElementById("moreInfo");

                                    data={
                                        nodes: nodeDatas,
                                        edges: edgeDatas
                                    };

                                    var options = {
                                        autoResize: true,
                                        height: '100%',
                                        width: '100%',
                                        edges: {
                                            color: 'rgba(141, 198, 063, 1)',
                                            smooth: false,
                                            arrows: {to: true}
                                        },
                                        layout: {
                                            randomSeed: undefined,
                                            hierarchical: {
                                                improvedLayout: true,
                                                enabled: true,
                                                levelSeparation: 150,
                                                nodeSpacing: 100,
                                                treeSpacing: 200,
                                                blockShifting: true,
                                                edgeMinimization: true,
                                                parentCentralization: true,
                                                direction: 'UD',        // UD, DU, LR, RL
                                                sortMethod: 'directed'   // hubsize, directed
                                            }
                                        },
                                        nodes: {
                                            color: {highlight:{background: '#ddd', border:'rgba(141, 198, 063, 1)'}, background: 'rgba(141, 198, 063, 1)', border: 'rgba(141, 198, 063, 1)', hover:{ background:'#ddd',border:'rgba(141, 198, 063, 1)'}},
                                            shape: 'box'
                                        },
                                        physics: false,
                                        interaction: {
                                            hover: true,
                                            dragNodes: false, // do not allow dragging nodes
                                            zoomView: false, // do not allow zooming
                                            dragView: true // allow dragging
                                        }
                                    };

                                    var network = new vis.Network(myDiv, data, options);

                                    $.getJSON('edges.php', function(edges){
                                        edgeDatas.add(edges);
                                    });
                                }
                            });
                        }  
                    }); 
                });
            });