mardi 30 avril 2019

Store checkboxes data from php to database

I have the following tables in my database:

CREATE TABLE subjects (
  subject_id int(11) NOT NULL AUTO_INCREMENT,
  subject text,
  PRIMARY KEY (subject_id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

CREATE TABLE users (
  id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  username varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE users_subjects (
  users_subjects_id int(11) NOT NULL AUTO_INCREMENT,
  user_id_fk int(11),
  subject_id_fk int(11),
  FOREIGN KEY(user_id_fk) REFERENCES users(id),
  FOREIGN KEY(subject_id_fk) REFERENCES subjects(subject_id),
  PRIMARY KEY (users_subjects_id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

In the table 'users_subjects' I’m trying to relate the 'subjects' and 'users' tables. All the data in the tables are entered from my index.php.

I introduce the subject_name from my index.php and every time I enter a new one, checkboxes like these are created in the part where the user is added:

enter image description here

This is the code to enter the user, where checkboxes are formed every time a subject is introduced (index.php):

<form method="post" action="register.php">
    <?php include('errors.php'); ?>
    <div class="input-group">
        <label>User</label>
        <input type="text" name="username" value="">
    </div>
    <div class="input-group">
        <label>Subjects</label>
    </div>
    <div>
        <?php
        $sql = "SELECT subject FROM subjects"; /*Select from table name: subjects*/
        $result = $conn->query($sql); /*Check connection*/
        if($result)
        {
            foreach($result as $row)
            {
                echo "<input type='checkbox' name='subject' value='" . htmlspecialchars($row['subject']) . "' /> <label>" . $row['subject'] . " </label><br>";
            }
        }
        ?>
    </div>

    <div class="input-group">
        <button type="submit" class="btn" name="reg_user">Add new user</button>
    </div>
</form>

I have managed to enter the user name in the 'users' table.

The problem I have is that I don’t know how to shore the checkboxes data in the 'users_subjects' table. I'm stuck and I can’t get it solved. Can somebody help me?

This is the code I’ve done for ‘register.php’:

<?php
$username = "";
$subject = "";
$errors = array();

include('Conexion.php');

if (isset($_POST['reg_user'])) {
    // receive all input values from the form
    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $subject = mysqli_real_escape_string($conn, $_POST['subject']);


    if (empty($username)) { array_push($errors, "Username is required"); }
    if (empty($subject)) { array_push($errors, "Subject is required"); }

    $user_check_query = "SELECT * FROM users WHERE username='$username' LIMIT 1";
    $result = mysqli_query($conn, $user_check_query);
    $user = mysqli_fetch_assoc($result);

    if ($user) { // if user exists
        if ($user['username'] === $username) {
            array_push($errors, "Username already exists");
        }
    }
    // Register user if there are no errors in the form
    if (count($errors) == 0) {
        $query = "INSERT INTO users (username) 
           VALUES('$username')";
        mysqli_query($conn, $query);


        $insert_id = mysqli_insert_id($conn);
        $subject=implode(',',$_POST['subject']);
        //Count subjects and checks if the subject exists
        for($i=0; $i<count($subject); $i++) {

            $query = "SELECT subject_id FROM subject where subject='$subject[$i]'";
            $result = $conn->query($query); /*Check connection*/

            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();
                $subject_id = $row["subject_id"];
                $query = "INSERT INTO users_subjects (user_id_fk, subject_id_fk)
           VALUES('$insert_id', '$subject_id')";
                mysqli_query($conn, $query);
            } else {
                /*???*/
            }
        }



        header('location: indexAdmin.php');
    }
}
?>




How to get multiple checkbox values in a single

I have a table with checkbox in single td. I have to find value for every checkbox in the table.How can I achieve.




How to create an editable html checkbox table in php and mysql?

I've created a html checkbox table whose data get's saved in the mysql database. I want to make it editable, the user should be able to uncheck the checked boxes or check some new boxes and the data should be saved and delete in the database accordingly.

The checked data gets saved in "c1-r1, c1-r2" format.

<?php


        $active = "report";
    `require_once 'pages/header.php';
    require_once './functions/schema-functions.php';
    require_once './functions/report-functions.php';

       $course = Schema::getCourse();
       $objective = Schema::getObjective();
       $goals = Report::getGoals();
       $mainobj = Report::getMainObjectives();
       $subobj = Report::getSubObjectives();
    ?>

    <form id="addReport" action ='./functions/report-functions.php' method="post">

    <table id="table1" class="table table-hover">

        <thead>
        <?php
        echo '<tr><th>Goals</th>';
        for ($i = 0; $i < count($course); $i++) {
            echo '<th id = "rotate1" >'. $course[$i]->commonName . '</th>';            
        }
        echo '</tr>';   
        ?>
        </thead>
            <tbody>

        <?php
        for ($y = 0; $y < count($goals); $y++) {           
            echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>

            </tr>';           
       ?>

        <?php
        for( $z = 0; $z < count($mainobj); $z++){
      if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
            echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>

        </tr>';
         ?>

        <?php

        for ($j = 0; $j< count($subobj); $j++) {
           if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
           echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';

       for ($x = 0; $x < count($course); $x++) {


          echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";

            }
            echo '</tr>';
        }
       }
      }
     }
    }       
            ?>       
            </tbody>       
    </table>
    <button class="button" name= "submit" value= "Submit">Submit</button>
</form>



<?php
require_once 'pages/footer.php';
require_once 'pages/close.php';
?>

The table should be editable and the checkboxes should be visible to the user. The user should also have the ability to make the changes and the new changes should be reflected in the same table.




Get list of checked checkboxes from recyclerview

I have a Recyclerview that contains a number of checkboxes. these checkboxes received from API(Checkboxes text and id). I want to get a list of ids of checked checkboxes to send to the server. One of my solutions is :

  1. create a data model(Info_Checkbox) that contain method get and set ID.
  2. create ArrayList.
  3. set checked checkboxes id to this array list and use this array to send params to server.

But my code is incorrect! when I checked a number of checkboxes, array list save the last checkboxes id. can you say another solution or fix this error?

Context context;
public ArrayList<Info_Filter> items = new ArrayList<>();
public SparseBooleanArray array = new SparseBooleanArray();
public ArrayList<Info_Checkbox> checkboxes = new ArrayList<>();
private Info_Checkbox info_checkbox = new Info_Checkbox();
public AdapterRecyFilterGroup(Context context, ArrayList<Info_Filter> items) {
    this.context = context;
    this.items = items;
}
@NonNull
@Override
public SetViewHolderFilter onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.sample_filter_grouping, viewGroup, false);
    return new SetViewHolderFilter(view);
}
@Override
public void onBindViewHolder(@NonNull SetViewHolderFilter setViewHolderFilter, int i) {
    setViewHolderFilter.checkBox.setText(items.get(i).getName());
    if (array.get(i)) {
        setViewHolderFilter.checkBox.setChecked(true);
    } else {
        setViewHolderFilter.checkBox.setChecked(false);
    }
}
@Override
public int getItemCount() {
    return items == null ? 0 : items.size();
}

public class SetViewHolderFilter extends RecyclerView.ViewHolder {
    CheckBox checkBox;
    public SetViewHolderFilter(@NonNull final View itemView) {
        super(itemView);
        checkBox = itemView.findViewById(R.id.cb_filter);
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (array.get(getAdapterPosition())) {      //!checked
                    array.put(getAdapterPosition(), false);
                    info_checkbox.setId(items.get(getAdapterPosition()).getId());
                    checkboxes.remove(info_checkbox);
                } else {        //checked
                    array.put(getAdapterPosition(), true);
                    info_checkbox.setId(items.get(getAdapterPosition()).getId());
                    checkboxes.add(info_checkbox);
                }
                notifyDataSetChanged();
            }
        });
    }
}




lundi 29 avril 2019

How to unchecked all checked checkbox in angular 6

I have a dynamic list data which have shown in checkbox. I click on multiple checkbox then multiple data saved in to an array and i saved that. After save the array the checkbox will be unchecked but it can't. I want to unchecked the selected checkbox after save the array. Please help me to find solution. Thanks.

stackblitz link here

// ts file

export class AppComponent  {
 userRoleListTemp: any = [];
 userRoleListToSave: any = [];
 checkedInfo: any;

 appUserRoleList: any = [
    {id: '1', roleName: 'SETUP_ROLE'},
    {id: '2', roleName: 'ENTRY_ROLE'},
    {id: '3', roleName: 'SEATPLAN_ROLE'},
    {id: '4', roleName: 'MARKSENTRY_ROLE'},
    {id: '5', roleName: 'APPLICANT_ROLE'}
 ];

 constructor() {}

 onChangeRole(userRole: string, isChecked) {
    this.checkedInfo = isChecked;
    if (isChecked.target.checked) {
        this.userRoleListTemp.push(userRole);
    } else {
        let index = this.userRoleListTemp.indexOf(userRole);
        this.userRoleListTemp.splice(index, 1);
    }
  }

  checkedEvnt() {
    this.checkedInfo.target.checked = false;
  }

}

// html file

<h1>Unchek All Roles</h1>

 <div class="form-check" *ngFor="let appUserRole of appUserRoleList">

 <input class="form-check-input" name="" 
   type="checkbox" id="" 
   (change)="onChangeRole(appUserRole.roleName, $event)">

 <label class="form-check-label" for="">
  
 </label> 

</div>
<button (change)="checkedEvnt()">Uncheck All</button>

<pre></pre>




How do I get the id of checked checkboxes from recyclerview?

I have a recyclearview with A few checkboxes. text and id of checkboxes received from the API. I should send id of checked checkboxes to API. now, I have two problems:

  • how to get checked checkboxes ids and store in a String value? this the string must be used in the activity.
  • when a user clicks to checkbox and this checked, id of checkbox save in String. now, User regrets and unchecked checkbox. in String, the id of checkbox should remove.

can you help me?




How to use multiple OnCheckedChangeListener for two or more groups of Android checkboxes

I am creating an Android application where I use two or more checkbox groups.

I dynamically create checkbox and OnCheckedChangeListener, I need to group the checkboxes in groups to limit the number of checkboxes that should be selected.

I have my class products and each product has extras, for some products there are 1 or more extras. Of which each extra I can select 1 or more ingredients.

The problem is that the Listener works for any checkbox, I can not assign a listener for each group of checkboxes.

How can I implement multiple listeners for each group of checkboxes?

I have already tried to put in a for the creation of a new OnCheckedChangeListener but everything works as a single checkbox group, not as a new one.

         for(int j = 0; j < extras.size(); j++){

            extra = extras.get(j);
            //Si los extras son checkboxs
            final LinearLayout layoutCheckBoxs = new LinearLayout(this);
            ViewGroup.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            ((LinearLayout.LayoutParams) lp).setMargins(16,16,16,16);
            layoutCheckBoxs.setOrientation(LinearLayout.VERTICAL);
            layoutCheckBoxs.setId(j+1);
            layoutCheckBoxs.setTag(j);
            final CheckBox[] checkBoxes = new CheckBox[extra.getListIngredients().size()];

            CheckBox.OnCheckedChangeListener checker = new CheckBox.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton cb, boolean b) {
                    if (count == extra.getMaxSelect() && b) {
                        cb.setChecked(false);
                        Toast.makeText(getApplicationContext(),
                                String.format("Solo puedes seleccionar %s %s",extra.getMaxSelect(),extra.getMaxSelect()==1?"extra":"extras"), Toast.LENGTH_SHORT).show();
                    } else if (b) {
                        count++;
                        Log.e("Count",String.valueOf(count));
                        extrasCompleted[Integer.valueOf(layoutCheckBoxs.getTag().toString())] = count;

                        enabledButtonAddCart(extras);
                    } else if (!b) {
                        count--;
                        Log.e("Count",String.valueOf(count));
                        extrasCompleted[Integer.valueOf(layoutCheckBoxs.getTag().toString())] = count;
                        enabledButtonAddCart(extras);
                    }
                }
            };

            for(i = 0; i < extra.getListIngredients().size(); i++){
                checkBoxes[i] = new CheckBox(this);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkBoxes[i].setTextAppearance(R.style.customCheckBoxStyle);
                }else{
                    checkBoxes[i].setTextAppearance(this,R.style.customCheckBoxStyle);
                }
             /*   checkBoxes[i].setTypeface(type);*/
                String rightText = "+ "+fmt.format(extra.getListIngredients().get(i).getPrice());
                String leftText =  extra.getListIngredients().get(i).getName();
                CharSequence text = null;
                if(extra.getListIngredients().get(i).getPrice()!=0) {
                    text = new Truss()
                            .append(leftText)
                            .pushSpan(new LineOverlapSpan())
                            .append("\n")
                            .popSpan()
                            .pushSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_OPPOSITE))
                            .pushSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPriceExtras)))
                            .append(rightText)
                            .build();
                }else{
                    text = new Truss()
                            .append(leftText)
                            .pushSpan(new LineOverlapSpan())
                            .append("\n")
                            .popSpan()
                            .build();
                }
                checkBoxes[i].setText(text);
                checkBoxes[i].setId(i);
                checkBoxes[i].setPadding(16,16,16,16);
                //setMargins(checkBoxes[i],15,5,15,5);
                setMargins(checkBoxes[i],15,15,15,15);


                checkBoxes[i].setOnCheckedChangeListener(checker);
}




Build checkboxes with PHP from mysql

I have the following table in my database:

CREATE TABLE subjects (
  subject_id int(11) NOT NULL AUTO_INCREMENT,
  subject text,
  PRIMARY KEY (subject_id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

In the table I have already entered some data (subject names).

What I'm trying to do is that for each subject in the table, a checkbox is created with the name of the subject next to it.

So far I have managed to create checkboxes for each subject in the table, but I can not get the name of the subject shown next to the checkbox. Does anyone know how to do it?

I'm doing it this way:

<?php
$sql = "SELECT subject FROM subjects"; /*Select from table name: subjects*/
$result = $conn->query($sql); /*Check connection*/

if($result)
{
    foreach($result as $row)
    {
        echo "<input type='checkbox' name='data[]' value='" . htmlspecialchars($row['subject']) . "' /> <label>Here goes the subject name</label>";
    }
}
?>




Grails how to use a checbox tag like a select tag

Hello everyone I need your help, I'm using grails and I'm trying to show a list of available users and you can select one or several, and those that are already selected are marked and those that can not be marked, currently works with the tag select but that only shows me the name and I can select one or several but I need to keep ctrl, that's why I want a checkbox to appear on the left and on the right the name of the user and if it is selected function same as in the select tag when saving.

This is my code with select tag:

<g:select name="abogados"
          from="${User.list()}"
          multiple="yes"
          optionKey="id"
          style="width:500px;font-size: 15px;height: 500px;text-align: center"
          value="${userInstance?.abogados}" />




How to nest checkbox in a and change element in another upon :checked?

When I'm nesting my checkboxes in a element my code stops working. I need images to display upon checking a certain checkbox. Code works without nesting the checkboxes in a .

I want my checkboxes to be nested in a so that it changes the display value from none to inline-block in the with the images upon selecting a certain checkbox.

I've tried everything but I think I just can't get my head around this problem.

<body>

<style>
  input[type=checkbox]:checked.ivo ~ div #fotoivo {
    display: inline-block;
 }

input[type=checkbox]:checked.ian ~ div #fotoian {
    display: inline-block;
 }

input[type=checkbox]:checked.non ~ div #fotonon {
    display: inline-block;
 }

#fotoivo {
    width: 200px;
    display: none;
}

#fotoian {
    width: 200px;
    display: none;
}

#fotonon {
    width: 200px;
    display: none;
}
</style>

<!--Checkboxes (works without the <div> wrapped around)-->
<!--<div>-->
  Ivo: <input type="checkbox" name="ivoian" class="ivo">
  Ian: <input type="checkbox" name="ivoian" class="ian">
  Non-binair: <input type="checkbox" name="ivoian" class="non">
<!--</div>-->

<!--Images that should change from display: none to inline-block.-->
  <div>
    <img id="fotoivo" src="ivo.jpg" alt="#">

    <img id="fotoian" src="ian.jpg" alt="#">

    <img id="fotonon" src="non.jpg" alt="#">
  </div>

</body>




Cannot get the column specific timestamp to display on checkbox

I have set up a Google sheet for attendance of Employees on which clicking on the checkbox, the current time is recorded.

I cannot get the specific timestamp in the respective columns when the checkbox is ticked.

Clicking on a different checkbox also change the timestamp for previously checked checkboxes.

I have used this formula here : =If(B2 = TRUE,now(),"") and used filter handle to apply the formula for other rows underneath.

I have used this formula: =If(B2 = TRUE,now(),"") The sheet can be seen here: https://docs.google.com/spreadsheets/d/1p6jmnHXtCu2m7BdLfC-23A51MrwkJJJpXidpbsDwxfU/edit?usp=sharing

I want to record the current timestamp, for each row. i.e on clicking of the checkbox the current time should be changed/recorded only for the column in the same row and not for other records.




dimanche 28 avril 2019

How to get rowData on checkbox change in jqwidgets?

I have used jqxDataTable in Angular with a checkbox. but I'm not getting value on checkbox change event

Please give me the solution for how to get rowData on checkbox change.




How to count checked checkbox using laravel?

we can count checked value of checkbox using js, jquery, etc. But there is no available source that gives how to count it using Laravel




Trying to create a script for a Google Sheets project that will toggle on off select groupings of rows

I have a Google Sheet setup that has about 160 rows. Rows are broken down into groupings, maybe 10 rows each fall under a Heading Group (Group01, Group02). Each of the ~10 items under each heading have a checkbox associated with it, then when checked on, will hide the selected row.

I'd like to put a checkbox in the HEADING ROW, that when checked, will hide the corresponding grouped rows below it, and show them when unchecked.

Thank you for any insight you can provide! I can tweak to suit but just can't find anything out there that I can readily tweak to fit my needs.

I've spent a few hours googling trying to find a solution I can implement to no avail.

I don't have anything yet.

Right now, I have the checkboxes for the headings located in column E.

For example, the first heading is "DESTINATIONS" on row 10. Under this category, there are 9 items. I'd like to be able to tic that checkbox in the "DESTINATIONS" heading (specifically Cell E10) that will hide rows 11-19.

There will be subsequent (~8 more similar headings/rows to toggle after this one as well.




Allow only one selection of check while other option disable in Ionic 3

I have been following this solution

How to get selected only single checkbox from multiple checkboxes using ionic 2 and angular2 its working fine but the issue is

When i check any checkbox the other gets disabled (which is what i want) but if i uncheck the same checkbox the other still remains disabled. How do i enable them after the checkbox is unchecked?

here is my code .ts file

export class list {
checkedIdx = -1;
}

.html file

<ion-card class="ion-card">
  <ion-item *ngFor="let item of options; let i=index">
    <ion-label></ion-label>
    <ion-checkbox item-left [ngModel]="checkedIdx == i"(ngModelChange)="$event ? checkedIdx = i : checkedIdx = -1" [disabled]="checkedIdx >= 0 && checkedIdx != i"></ion-checkbox>
  </ion-item>
</ion-card>




samedi 27 avril 2019

Remove required checkbox border in Firefox

If a checkbox is required, Firefox will apply a red border to it, even if the form has not yet been submitted. How can I remove or prevent this border?

<input type='checkbox' required />

enter image description here

I tried applying the following styles, none of which worked. Now I'm out of ideas :/

input[type=checkbox]:invalid {
  -moz-appearance: none;
  appearance: none;
  border: none;
  outline: none;
}




Dynamic accordion style checkbox menu in angular

I want to create a select menu with dynamic accordion style checkbox options same as the picture below:

enter image description here

or like this:

enter image description here

My data looks like this:

 let allowedShifts = [{
    category: "Days",
    name: "D"
},
{
    category: "Evenings",
    name: "E"
},
{
    category: "Nights",
    name: "N"
},
{
    category: "Days",
    name: "d"
},
{
    category: "Nights",
    name: "n"
}];

I tried to implement the same using multiple select menu but was not able to pipe filter the data based on category. Here is my code for the reference:

HTML:

<select multiple class="form-control" name="shifts" id="exampleSelect2" [(ngModel)]="allowedShifts">
<optgroup label="Days">
    <option [value]="shiftIcon.name" *ngRepeat="let shiftIcon in allowedShifts | filter: {category: 'Days'}">
        
    </option>
</optgroup>
<optgroup label="Evenings">
    <option [value]="shiftIcon.name" *ngRepeat="let shiftIcon in allowedShifts | filter: {category: 'Evenings'}">
        
    </option>
</optgroup>
<optgroup label="Nights">
    <option [value]="shiftIcon.name" *ngRepeat="let shiftIcon in allowedShifts | filter: {category: 'Nights'}">
        
    </option>
</optgroup>




vendredi 26 avril 2019

Checkbox is not checked, even though I do it with code

I'm writing a Java Game similar to Tetris for a school project. In the game I have a checkbox to turn music on/off.

My problem is that the checkbox, even though I set it to be checked, is NOT checked when I click it (don't understand me wrong, not AFTER, but before/at the same moment when I clicked it).

Okay so, in my code where I first initialize the checkbox I set it to be checked based on a variable provided in another class.

I tried debugging everything that is going on with the checkbox but I didn't get anything I didn't already knew.

Here's the code where I initialize the box:

music_cbox = TexturesHandler.getCheckboxTemplate();
music_cbox.setName("Music");
music_cbox.addMouseListener(Retris.getButtonHandler());
music_cbox.setLocation(Retris.WIDTH / 2 - 25, 250);

 // Setting it to checked based on the variable

if(!Retris.getAudioHandler().canPlay()) {
    music_cbox.setIcon(TexturesHandler.getUncheckedCheckBoxStyle());
    music_cbox.setSelected(false);
    System.out.println("box not selected");
} else {
    music_cbox.setIcon(TexturesHandler.getCheckedCheckBoxStyle());
    music_cbox.setSelected(true);
    System.out.println("box selected");
    }

The canPlay variable only gets changed when you CLICK the box:

if(box.isSelected()) {
    Retris.getAudioHandler().canPlay(false);
    Retris.getAudioHandler().stopMusic();
    System.out.println("Music disabled");
    box.setIcon(TexturesHandler.getUncheckedCheckBoxStyle());
    break;
    // (in a switch statement)
} else {
    Retris.getAudioHandler().canPlay(true);
    Retris.getAudioHandler().startMusic("Main_Menu.wav", "Main Menu", 0.1F);
    System.out.println("Music enabled");
    box.setIcon(TexturesHandler.getCheckedCheckBoxStyle());
    break;
}

I also tried box.setSelected() after setting the new icon and all, but somehow when i first click the box, it does the else part instead of the if part.




M13Checkbox Selected Action in Swift?

I'm using the M13Checkbox pod. I want to print "remember me" to labeltextfield when checkbox is checked, and "remember me" when Checkbox is not checked. When I click it, it just says, "don't remember me."

  let checkboxm13: M13Checkbox = {

        let checkboxe = M13Checkbox()
        checkboxe.stateChangeAnimation = .stroke
        checkboxe.addTarget(self, action: #selector(checkboxvalue(sender:)), for: .valueChanged)
        return checkboxe

    }()
 @objc func checkboxvalue(sender: Checkbox) {
        if sender.isSelected == true {
            labelcheckbox.text = ("Beni Hatırla")

        }
        if sender.isSelected == false {
            labelcheckbox.text = ("Hatırlama")           
        }       
    }




How to retrive multiple selected checkbox in edit form which is selected checkboxes at the time add form. in angular 7

I am selected checkbox which is i want in Units and i post it to database by using angular 6. But at the time of get selected Unit checkbox by use [checked]="is_selected" not working means its not shows me which is i selected checkbox only all units are shown.

I already tried to getByProduct and tries also to check which is selected Unit in my product and is selected value = Unit_id in Unit class then its get true. its also changed to true in console. But i have problem its not changed in Unit class is_selected is true or false. and I cant initialise the Unit class to constructor as new Unit() to work fine

                                  Product.component.ts
  Productitems: Items[];
  units: Array<Unit> = [];
  Unititems : Unit[];
  complexForm: FormGroup;
  formData: FormData;
  model : Items;
  unit_id: number[] = [];

  constructor() 
  {
    this.model = new Items();
   }

getProductByID(Id: string): Items {
  let params: any = {};
  params.product_id = Id;
  this.unit_id = [];
  this.Item_Service.getAllUnits().subscribe(response => {
  this.units = response;
   this.Item_Service.getProducts_ById(params).subscribe(
    responce => {
     this.model = responce;
     this.units.forEach(x => {
      this.model.unit_id.forEach(y => {
        if (x.unit_id == y) {
          x.IsSelected = true;
          this.unit_id.push(x.unit_id);
     }
    })
   })
  },
 err => { console.log(err); });
 },
 err => { console.log(err); });
  return this.model;
}


export class Unit {
    public IsSelected: boolean;
    constructor() {
        this.IsSelected = false;
    }
}

<div class="col-lg-3 col-md-4 col-sm-4 col-xs-12"  *ngFor="let item of Unititems">
 <div class="form-group">
  <div class="checkbox checkbox-primary">
   <input id="checkbox"class="styled" type="checkbox"
     (change)="onChangeunit_id(item.unit_id, $event.target.checked)"
      [checked]="IsSelected">
    <label for="checkbox">
         
    </label>
   </div>
  </div>
</div>

enter image description here




insert loop checkbox data in database in php

i am trying to insert data in the database but only those data which are checked. Its working fine with update query but don't know why its is not working for insert query. Suppose, when i check 10 options and click on 'Move All' button, it is working fine but when i replace the update query with insert query, it is inserting blank data in database.

Here is my full code:

<?php 
include("config.php");
if(isset($_POST['save'])){
  $checkbox = $_POST['check'];
  for($i=0;$i<count($checkbox);$i++){
  $del_id = $checkbox[$i]; 

  $firm_name_sms=$_POST['firm_name_sms'];
  $position_sms=$_POST['position_sms'];
  $city_sms=$_POST['city_sms'];
  $catagory_name_sms=$_POST['catagory_name_sms'];
  $PrimaryMobile_no_sms=$_POST['PrimaryMobile_no_sms'];

  $bulksms="INSERT INTO bulk_sms (firm_name_sms, position_sms, city_sms, catagory_name_sms, PrimaryMobile_no_sms) VALUES('$firm_name_sms', '$position_sms', '$city_sms', '$catagory_name_sms', '$PrimaryMobile_no_sms')";
  $smsquery=mysqli_query($conn, $bulksms);
}
}


$sql="SELECT * FROM inventory_details where status ='0' AND role='0' limit 0,100";  
$query=mysqli_query($conn, $sql);

?>


<form method="post" action="">
<div class="container">
  <?php
$i=0;
$today_date=date("Y-m-d H:i:s", time()); 
    while($row=mysqli_fetch_assoc($query)){
    $id = $row['id'];
    $inventorybackground = $row['inventorybackground'];
    $inventorycolor = $row['inventorycolor'];
    $firm_name = $row['firm_name'];
    $position = $row['position'];
    $city = $row['city'];
    $catagory_name = $row['catagory_name'];
    $PrimaryMobile_no = $row['PrimaryMobile_no'];
  ?>

    <div class="row" style="background-color: <?php echo $inventorybackground; ?> !important; color: <?php echo $inventorycolor; ?>; padding-top: 10px;">
        <div class="col-md-1 inventory-data">
          <input type="text" class="form-control" name="id_sms" value="<?php echo $id;?>" disabled>
        </div>

        <div class="col-md-3 inventory-data">
          <input type="text" class="form-control" name="firm_name_sms" value="<?php echo $firm_name;?>" disabled>
        </div>

        <div class="col-md-1 inventory-data">
          <input type="text" class="form-control" name="position_sms" value="<?php echo $position;?>" disabled>
        </div>

        <div class="col-md-2 inventory-data">
          <input type="text" class="form-control" name="city_sms" value="<?php echo $city;?>" disabled>
        </div>

        <div class="col-md-2 inventory-data">
          <input type="text" class="form-control" name="catagory_name_sms" value="<?php echo $catagory_name;?>" disabled>
        </div>

        <div class="col-md-2 inventory-data">
          <input type="text" class="form-control" name="PrimaryMobile_no_sms" value="<?php echo $PrimaryMobile_no;?>" disabled>
        </div>

        <div class="col-md-1 inventory-data"><input type="checkbox" id="checkItem" name="check[]" value="<?php echo $row["id"]; ?>"></div>
    </div>

<?php
$i++;
}
?>

</div>

<p align="center"><button type="submit" class="btn btn-success" name="save" style="margin-bottom: 150px;">Move All</button></p>
</form>
<script>
$("#checkAl").click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
</script>

when i replace the insert query i.e

  $firm_name_sms=$_POST['firm_name_sms'];
  $position_sms=$_POST['position_sms'];
  $city_sms=$_POST['city_sms'];
  $catagory_name_sms=$_POST['catagory_name_sms'];
  $PrimaryMobile_no_sms=$_POST['PrimaryMobile_no_sms'];

  $bulksms="INSERT INTO bulk_sms (firm_name_sms, position_sms, city_sms, catagory_name_sms, PrimaryMobile_no_sms) VALUES('$firm_name_sms', '$position_sms', '$city_sms', '$catagory_name_sms', '$PrimaryMobile_no_sms')";
  $smsquery=mysqli_query($conn, $bulksms);

with update query i.e.

$bulksms="UPDATE inventory_details SET role='3' WHERE id='".$del_id."'";
  $smsquery=mysqli_query($conn, $bulksms);

the it is working fine. Please help me out, Thank you




jeudi 25 avril 2019

Pass multiple checked checkbox values to TextInput in React Native

Any idea how can we pass the items that has a checked checkbox? like if I checkbox no: 1,2,3 and etc.. then pass these to the Text Input

We can you can store the selected item in a class variable, for e.g this.selectedItem = item; when check box is true. Now you can use selectedItem anyway and anywhere you want, but I need to store multiple values.

Need to pass multiple checked checkbox values to TextInput React Native.




Custom checkbox with CSS ::before - not working in Firefox/Edge

I have come up against a very annoying CSS issue while trying to get a project working cross-browser (not bothered about IE, it's only a hobby project, but it would be nice to get it working on all modern browsers at the very least). It relates to some checkboxes which I wish to apply custom styles to - I know you can't do very much with the standard HTML <input type="checkbox"> so I have done what is recommended in many places, and used a ::before pseudo-element. And I was pleased with the result in Chrome. Imagine my surprise when I find that my custom checkbox simply doesn't display at all in Firefox!

I've been playing with this for a few hours and have stripped it right back to the very root of the problem - and it's something to do with the checkbox itself, rather than any other CSS it's interacting with. Here's the bare minimum example:

input[type="checkbox"] {
    visibility: hidden;
}

input[type="checkbox"]::before {
    visibility: visible;
    content: "";
    display: block;
    width: 1.1em;
    height: 1.1em;
    color: #eddc23;
    border: 1px solid #eddc23;
    background-color: #540123;
    border-radius: 35%;
    line-height: 1.27;
    text-align: center;
    cursor: pointer;
}

input[type="checkbox"]:checked::before {
    content: "\2713";
}
<input type="checkbox">

This should show a dark red checkbox which has a yellow tick when selected. It works perfectly on Chrome and Opera, but not at all on Firefox or Edge. (Here's a codepen link of the same in case the Stack Overflow snippet somehow exhibits different behaviour.) CSS isn't one of my strong points and despite a few hours of experimenting and googling, I'm baffled.

Would appreciate any pointers, not only as to how to get this working cross-browser, but as to why it's not working on FF/Edge. (Inspecting the element on Firefox shows no sign of a ::before pseudo-element at all. I've also ruled out it being to do with the empty content property, since changing that to real text fails to make it visible in the browsers concerned.)

Thanks in advance.




Angular 6: Disable dynamic checkbox based on condition

I have a dynamic form with repeated checkbox list. Please see https://stackblitz.com/edit/angular-5jdnb5

If a checkbox option is checked in one checkbox list, the same option has to be disabled in other lists. For example, if option Life is checked in first list, the Life checkbox should be disabled in other lists.

How do i implement the logic. Please suggest.




unchecking checkbox doesnt remove id from arraylist

I am doing functionality of checkbox and it is working fine for checked but when i uncheck the checkbox it gives error.. and one thing when i checked the checkbox i am storing id of that item into arraylist and i want to remove that id when uncheck the checkbox

final CheckBox checkBox = listViewItem.findViewById(R.id.edit);


        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (buttonView.isChecked() ) {
                    proUseritems.add(String.valueOf(heroList.get(position).getProfile_id(position)));
                    Toast.makeText(mCtx, "" + proUseritems.toString(), Toast.LENGTH_SHORT).show();
                }
                else {



                        proUseritems.remove(position);
                        Toast.makeText(mCtx, "" + proUseritems, Toast.LENGTH_SHORT).show();

                 }
            }
        });




mercredi 24 avril 2019

How to set checkbox state based on IDs getting from API response in Android

I'm having a RecyclerView which has a list of items getting from one API response. I want to show checked state of those recyclerView checkboxes based on another API response i.e in 2nd API response i have some Array of Integers(FacId) shown in image.Based on those Array i want to set the checkboxes state of recyclerView.

Api Response public View onCreateView( @NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {

    view = inflater.inflate(R.layout.hostel_create_four, container, false);
    context = getActivity();
    unbinder = ButterKnife.bind(this, view);

    btnNext = view.findViewById(R.id.Id_SaveFacilitiesData);
    btnPrevious = view.findViewById(R.id.previous);
    recyclerView = view.findViewById(R.id.facilitiesRecyclerView);

    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Next();
        }
    });
    btnPrevious.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Previous();
        }
    });
    try {
        String check = JocoroApplication.getInstance().getContentType();
        if (check.equalsIgnoreCase("Update")){
            isUpdate = true;
            detailsModel = JocoroApplication.getInstance().getHostelModel();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    facilitiesList();

    return view;
}

public void Next() {
    listener.OnPageChanged(4);
}
public void Previous() {
    listener.OnPageChanged(3);
}

public void facilitiesList(){
    ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
    Call<Object> call = apiInterface.getHostelFacilities();
    ApiRequest.getInstance().serviceCalls(getActivity(), call, new ApiRequest.ServiceCallBack() {
        @Override
        public void successful(Response response) {
            Gson gson = new Gson();
            String target = gson.toJson(response.body());
            HostelResponseModel responseModel = gson.fromJson(target, HostelResponseModel.class);
            if (responseModel.getStatusCode() == 1){
                hostelDetailsModelArrayList = responseModel.getData();
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL,false));
                adapter = new HostelFacilitiesAdapter(hostelDetailsModelArrayList);
                recyclerView.setAdapter(adapter);
            }
        }

        @Override
        public void fail(Throwable t) {

        }
    });
}

public class HostelFacilitiesAdapter extends RecyclerView.Adapter<HostelFacilitiesAdapter.FacilitiesHolder>{
    ArrayList<HostelDetailsModel> hostelDetailsModelArrayList;

    public HostelFacilitiesAdapter(ArrayList<HostelDetailsModel> hostelDetailsModelArrayList) {
        this.hostelDetailsModelArrayList = hostelDetailsModelArrayList;
    }

    @NonNull
    @Override
    public FacilitiesHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_hostel_facility, parent, false);
        return new FacilitiesHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull FacilitiesHolder holder, int position) {
        HostelDetailsModel detailsModel = hostelDetailsModelArrayList.get(position);
        holder.facilityName.setText(detailsModel.getName());
        holder.checkBox.setChecked(detailsModel.isChecked());

    }

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

    public class FacilitiesHolder extends RecyclerView.ViewHolder {
        TextView facilityName;
        CheckBox checkBox;
        public FacilitiesHolder(@NonNull View itemView) {
            super(itemView);
            facilityName = itemView.findViewById(R.id.tvHostelFacilityName);
            checkBox = itemView.findViewById(R.id.cbFacility);
        }




How to get if checkbox is checked or not

So I have to make this soccer website where theres a list of checkboxes (i the registration) to select the prefered position. I want, for example, when someone inputs the center-attack checkbox and the goalie checkbox, to send me a list of the positions selected. As you can see, it's a picture with a list of checkboxes fo every position

The checkboxes layout

So i used this code to see if the checkbox in question is selected (duplicated for every checkbox/position):

if (document.getElementById("goalie").checked == true) {
    var Goalie = "Goalie";
};

Then, I combine all the strings with:

PreferedPositions = Goalie + " " + LeftDefense + " " + CenterLeftDefense + " " + CenterRightDefense + " " + RightDefense + " " + LeftMidfield + " " + CenterMidfield + " " + rightmidfield + " " + LeftAttack + " " + CenterAttack + " " + RightAttack + ".";

And I send it to php so I can email it to the owner with ajax:

$.ajax({
      type: "POST",
      url: "registration.php",
      data: {
            PostPreferedPositions: PreferedPositions
      },
success: function (res) {}
});

But when I test it out, the email comes out with:

"Prefered positions: undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined."

I understand all the undefined if I had selected none of the checkboxes. But this occurs no matter how many checkbox I have selected. Like if I had the goalie and center-attack selected, I would expect:

"Prefered positions: Goalie undefined undefined undefined undefined undefined undefined undefined undefined Center-Attack undefined."

But that's not the case. I know I can easily fix all the undefined by putting a else if in the statement, but I don't know why all the positions return as undefined.




How to stretch a CheckBox while maintaining everything aligned

I'm writing a custom checkable ListBox and the items must be checked when an item is selected. The easiest approach I could come up with is to increase the CheckBox height/width (size) to cover the whole ListBoxItem area, however I couldn't manage to vertically align the square and its text, eg:

enter image description here

The red text is somewhat the desired alignment, given its whole area (blue rectangle). What's necessary to achieve this?


For a complete explanation, keep on reading. My current control looks like bellow:

enter image description here

Some have pointed out to define a custom ListBox.ItemContainerStyle and having a setter to the IsSelected property to the same as the CheckBox bound property, eg:

<Setter Property="IsSelected" Value="{Binding SomeBooleanObjectProperty, Mode=TwoWay}" />

This is NOT what I want as this will keep items selected whether the SomeBooleanObjectProperty is true.

The custom control code was omitted due to not being related to this question. What I need is a custom sizeable vertically alignable CheckBox, independently whether it is going to be used in.




Difficulty Aligning Bootstrap Custom Checkboxes to the Right

I have a bootstrap 4 table in which I have custom checkboxes that I would like to align to the right.

For an example, please reference this fiddle

I have used this method to create the custom checkboxes:

<label class="custom-control custom-checkbox">
    <input type="checkbox" id="checkbox" class="custom-control-input">
    <span class="custom-control-indicator"></span>
    <span class="custom-control-label"></span>
</label>

So far, I have tried adding this CSS

.custom-control {
    padding: 0 !important;
    margin: 0 !important;
    width: 0px !important;
}

.custom-control-label::before {
  left: 0;
  padding-right: 0;
  margin-right: 0;
}

.custom-control-label::after {
  left: 0;
  padding-right: 0;
  margin-right: 0;
}

.custom-control .custom-checkbox {
  padding-right: 0;
  margin-right: 0;
}

As well as adding the .right and .pull-right classes to all of the checkbox elements to no avail.

This question solves it by using .pull-right Align CheckBox to the right using Bootstrap




request.form.getlist() not working with data from AJAX request

I'm having issues with checkboxes sharing the same name in Flask. Specifically, the form has a checkbox for each project, and I need to get a list of project ID's for each project that the user checked in the form. In the HTML, each project has a checkbox with name = 'project' and value = the project ID. Then, I try to extract a list of project id's using 'request.form.getlist('project') on the server side. However, all it gives me is an empty list.

HTML:

<form id = 'filterForm' action="" method='post' >
  <fieldset>
    <legend>Projects</legend>
      <input type="checkbox" name="project" value="1">Project A<br>
      <input type="checkbox" name="project" value="2">Project B<br
      <input type="checkbox" name="project" value="3">Project C<br
  </fieldset>
  <button type = 'button' class = 'ui small blue button' id = 'applyFilters'>Apply</button>
</form>

Flask:

@user_web.route('/get_admin_table', methods=['POST'])
@Auth.auth_required
def get_admin_table():
    projects = request.form.getlist('project')
    print(projects) #this returns an empty list.
    #...some other stuff

I've run print(request.form) to make sure the request was going through, and I get the following:

ImmutableMultiDict([('form[0][name]', 'project'), ('form[0][value]', '2'), ('form[1][name]', 'project'), ('form[1][value]', '1')])




select only one checkbox in a group not working 100%

Hello I'm trying to make it where the user can only select 1 checkbox at a time on a page.

Here's my code so far:

<script>
function onlyOne(checkbox) {
    var checkboxes = document.getElementsByName('active', 'inactive', 
'showall')
    checkboxes.forEach((item) => {
        if (item !== checkbox) item.checked = false
    })
}
</script>

and

<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="inactive" value="Yes" 
onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="showall" value="Yes" onclick="onlyOne(this)">

What keeps happening is it will work sometimes and sometimes they can select more than 1 checkbox. What do I need to tweak to get it working all the time.

Thanks




how detect the the checkbox checked event in formly angular?

Using formly and Json i created one form.now i want display one textbox when i checked the check box.

I tried with ngDoCheck() method but i unable to display the text box.this method hitted every field click event but i need checked event only.can any one help me out this.

{"columnName": "chkid","displayName":"","position":2,"columnType":5,"columnSize": 50,"sizeUnit": "px","isVisible": 1,"isEnabled": 1,"isRequired": 0,"isMultiSelect": 0,"showSuggestion": 1,"useDisplayValueOnly": 1,"listDataProvider": null,"discreteValues": null,"filterType": "e"},

enter image description here




Change class bg if checkbox is checked

I'm working on my portfolio website and need some help with a bit jQuery code. I want a parent class to react to the checkbox in it. In this case, the background color needs to change to #000 when the checkbox is active/checked.

I don't know what line of code to add to make my class react to the checkbox. I've searched on google on how to do it but didn't get much wiser. It's probably a really small thing but I would hope to get some help from you guys.

$("input[type='checkbox']").change(function() {
  if ($(this).is(":checked")) {
    $(this).parent();
  } else {
    $(this).parent();
  }
});
.product {
  background-color: #ccc;
  /* needs to change to #000 when active */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div class="product">
  <input class="check" type="checkbox" name="logo"> Logo 
</div>



Symfony 3 - JS- How to gray out a set of checkboxes at the click of a radio button?

in a twig view, which allows me to do statistics I display several things:

A group radio button that allows me to select either "Option A", "Option B", "Both".

And a set of checkboxes referring to user types. They will be displayed through a database query.

Like this :

<legend>Type : Sélectionner tout <input type="checkbox" id="selectAll" value="selectAll" class="selectAllCheckboxes"></legend>
                    

I already have a function in javascript allowing me to select all and deselect at once.

Now what I would like to do is this:

enter image description here

If I check "External", then I want that in the list of user types, the type "1st degree" is automatically checked, and that the rest can not be.

And conversely :

enter image description here

If "CAS" is checked, then all other types have the option to be checked, except the "1st degree" type.

But since I know absolutely nothing about javascript, and I display my user types through a database and I do not write them myself, I do not see how I take it. Thanks for your help !




How to submit unchecked checkboxes to controller

Ok first I have a "settings" table on my database in which I have the fields "name" and "value" its a configuration kind of table where the value could be anything from string to boolean values etc.

Now on my blade, I have a form with various inputs "texts" "selects" "checkboxes" etc. When submitting the form on the controller I run a foreach where for each attribute of the $request i store its key as the name and its value as its value on the database.

    $agency_id = Auth::user()->agency->id;
    $settings = AgencySettings::whereAgencyId($agency_id)->get();
    foreach ($request->except('_token') as $key => $value)
    {
        $setting = $settings->where('name','=',$key)->first();
        if (boolval($setting))
        {
            $setting->value = $value;
            $setting->update();
        }else{
            $setting = new AgencySettings;
            $setting->agency_id = $agency_id;
            $setting->name = $key;
            $setting->value = $value;
            $setting->save();
        }
    }

All works well except the unchecked checkboxes which are not inside the $request. I know I can handle them like so $request->has('name_of_checkbox') but because of the dynamic nature of the table on the database, I don't want to have hardcoded on my Controller the name of a specific setting.

My goal is that the code on my Controller will be the same regardless the number of different settings I will use on my frontend (maybe in the future there will be a need to add more).

So my question, is there a way to handle those checkboxes serverside without having to refer to them specifically, or a way to always return the value of the checkboxes to the server despite its state?

My first thought is to go with javascript and hidden inputs, but maybe there is a better way.




Radio and Checkbox button state cleared when clicking browser's back button

i have a problem with regards to checkbox button state when navigating to next page then click back button of Edge (MS) browser.

While digging for information about this problem, i came across this bug report. Since 2015, it has no updates. To date, is there any workarounds with this issue?

The use case is below;

  1. User access a page
  2. Tick's a checkbox or radio button
  3. Navigate to another page (either via address bar or clicking a link via tag)
  4. Once another page has been loaded, Click Edge's back button (or Alt + Left Arrow)
  5. Previous state/value of checkbox or radio button must persist or preserved.

Right now, state/value is cleared when navigating back to page via Back button of Edge.




mardi 23 avril 2019

React: State update delay

I'm trying to change state by checking radio button. When I check it, it updates the value only after I check the next radio button. If I click first radio button it won't change the state, and if I check the second one it updates state with the previously checked radio button's value. Can anyone help me fixing this?

class App extends React.Component {

    state = { checked: false, radioValue: '' }

    handleChange = (event) => {
        const target = event.target;
        const value = target.value;
        const name = target.name;

        console.log("this.state", this.state); // Gets previous value

        this.setState({
          [name]: value
        });
      }

    render() {

        return (
            <div className="wrapper">

                       <input
          name="radioValue"
          type="radio"
          value="aaa"
          checked={this.state.radioValue === 'aaa'}
          onChange={this.handleChange} />First Radio Button

            <br />

        <input
          name="radioValue"
          type="radio"
          value="bbb"
          checked={this.state.radioValue === 'bbb'}
          onChange={this.handleChange} />Second Radio Button

            </div>
        );
    }
}

export default App;




How to check checkbox on first click

I want to check checkboxes ”Vorträge”, ”Reisen”, ”Exkursionen” on click on link „to Vorträge”, „to Reisen”, „to Exkursionen”. But they only get activated after the second click on link. How can i check the checkbox on first click?

$(".nav-link").click(function(e) {
    var target = window.location.hash;
    var $targeta = $(target);
    $('html, body').stop().animate({
            'scrollTop': $targeta.offset().top - 100
        }, // set offset value here i.e. 100
        900,
        'swing',
        function() {
            window.location.hash = target - 40;

        });
    $targeta.prev().prop('checked', true);

});
</script>




Propagate ListBoxItem IsSelected trigger to child control

I'm developing a CheckedListBox with self removable ListBoxItems. The problem is that an item only gets checked if the user clicks on the CheckBox area, which is kind of awkward.

How do I create ListBoxItem triggers (IsSelected) to check the checkboxes on a "DataSourced" ListBox? Eg:

enter image description here

Below is my control (all other code have been omitted for brevity):

<ListBox x:Name="executors" ItemsSource="{Binding Executors}" HorizontalAlignment="Left" Height="121" Margin="23,19,0,0" VerticalAlignment="Top" Width="362">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Height" Value="30" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition />
                                <ColumnDefinition Width="30" />
                            </Grid.ColumnDefinitions>
                            <CheckBox Margin="4,8" IsChecked="{Binding Enabled}">
                                <ContentPresenter Content="{Binding Description}">

                                </ContentPresenter>
                            </CheckBox>
                            <Button Command="{Binding DataContext.RemoveExecutorCommand, ElementName=executors}" CommandParameter="{Binding}" Background="White" Height="22" Width="22" Grid.Column="1">
                                <Image Source="trash.png" Stretch="Fill" Width="14" Height="14" />
                            </Button>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Executors is a ObservableCollection of Executor which has Enabled and Description as members.




lundi 22 avril 2019

Django storing multilevel check boxes value in database

This is the layout i want to be displayed when the ModelForm is rendered(crispy form).

User selects the parent checkbox (e.g. Locations 1) which will automatically select the sub check-boxes but user can deselect some check-boxes (e.g. Locations 2).

After the selection the Values of the Devices id associated with the Announcement object need to be stored in the database.

models.py

class DeviceLocation(models.Model):
    location_name = models.CharField(max_length=500)

    def __str__(self):
        return self.location_name

class Device(models.Model):
    name = models.CharField(max_length=500)
    location = models.ForeignKey(DeviceLocation, on_delete=models.CASCADE)

    def __str__(self):
        return self.name


class Announcement(models.Model):
    submitted = models.ForeignKey(User, on_delete=models.CASCADE)
    which_device= models.ForeignKey(Device, on_delete=models.CASCADE)
    ad_name = models.CharField(max_length=500)

forms.py

class AnnouncementForm(forms.ModelForm):
    which_box = forms.ModelMultipleChoiceField(
         queryset=Device.objects.all(),
         widget=forms.CheckboxSelectMultiple())

    class Meta:
        model = Announcement




dimanche 21 avril 2019

checkboxes without form tags , no checked checkboxes found

so i've been working on this problm for like 2 days , i've tried all the solutions i found here
my problm is that i'm using checkboxes without form tag and i want to get the checked boxes into an array and return that array so i can insert the answers afterwards into a database but all i get is empty array even though i check


function recherche_salle ($conn,$datte,$begin,$end) 
{ 

$salle_libre= array(); 
$position=0; 
$str='';
$sql= "select  * from time_report_ where  new_date = '".$datte."' and  ('".$begin."' BETWEEN debut AND fin or '".$end."' BETWEEN debut AND fin)
UNION 
select  * from  events where  new_date = '".$datte."' and  ('".$begin."' BETWEEN debut AND fin or '".$end."' BETWEEN debut AND fin);"; 
$results = mysqli_query($conn,$sql); 
$resultscheck = mysqli_num_rows ($results); 

if ($resultscheck>0)  
{  
    while ($row= mysqli_fetch_assoc($results)) 
  { 
    array_splice( $salle_libre, $position, 0,$row['Salle']); 

    $position= $position+1;

  } 
} 

  $image= implode("','", $salle_libre);
   //echo $image; 
   $sqll= "SELECT DISTINCT Salle FROM liste_des_salles WHERE Salle NOT in ('$image') limit 1;";
   $resultss = mysqli_query($conn,$sqll); 
   $resultscheckk = mysqli_num_rows ($resultss); 
   if ($resultscheckk>0)  
 {  echo ("voici la liste des salles libres" ."<br>");
    while ($roww= mysqli_fetch_assoc($resultss)) 
   {   
       $str ='<br/>'.$roww['Salle'].'<input type="checkbox" value='.$roww['Salle'].' name="check[]" >'; 


    }



     echo $str; 
     if(isset($_post['check[]'])) 
      {$rooms=$_post['check[]'];}










 }

    return $rooms;    

}




Enabling/disabling radio buttons according to the state of a checkbox

I have a form with several checkboxes and, below each of those checkboxes, a set of radio buttons. I want to disable and reset radio buttons when the corresponding checkbox is not checked or unchecked.

I tried to enable the radio buttons using the jquery selector :radio[name=vid] but it doesn't work.

<form action='matrix.php' method='post' id='formanal' name='formanal'>
    <ul class="desc">
        <li><label><input type="checkbox" id ="1" value="Couleur des tarses" name="1">Couleur des tarses</label></li>
        <ul>
            <li class="valeur"><label><input type="radio" value="1-1" id="1-1" name="v1" disabled>Jaunes</label></li>
            <li class="valeur"><label><input type="radio" value="1-2" id="1-2" name="v1" disabled>Blancs</label></li>
        </ul>
    </ul>
    ...
    <ul class="desc">
        <li><label><input type="checkbox" id ="8" value="Forme des ailes" name="8">Forme des ailes</label></li>
        <ul>
            <li class="valeur"><label><input type="radio" value="8-15" id="8-15" name="v8" disabled>Pliées en long</label></li>
            <li class="valeur"><label><input type="radio" value="8-16" id="8-16" name="v8" disabled>Étalées en toit</label></li>
        </ul>
    </ul>
    <input type='submit' name='action' value='Valider'></div>
</form>

$(document).ready(function() {
    $("form input:checkbox").change(function() {
        var vid = 'v' + this.id;
        var etat = $(this).prop('checked');
        if (etat) {
            $(':radio[name=vid]').prop('disabled', false);
        } else {
            $(':radio[name=vid]').prop('checked', false);
            $(':radio[name=vid]').prop('disabled', true);
        }
    });
});

The radio buttons are disabled when created, but a click on the corresponding checkbox doesn't enable them. Thanks in advance for any clue.




Fix JS code: Append multiple values out of checkboxes to url

I found this code that replaced the link text (= "Show") by the checked checkbox values. Now, I am looking for a code that appends/removes the checked/unchecked values to the link url itself, e.g. does this:

<a href="/best/?price=123&amp;feature=Teamsport">Show</a>

Here is the code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <input type="checkbox" name="options[]" value="Teamsport" />
  <input type="checkbox" name="options[]" value="Individual sport" />
</div>

<div><a href="/best/?price=123&amp;feature=">Show</a></div>

And

function calculate() {
var arr = $.map($('input:checkbox:checked'), function(e, i) {
    return +e.value;
});
$("[href$='feature=']").text('the checked values are: ' + arr.join(','));
}

calculate();
$('div').delegate('input:checkbox', 'click', calculate);




samedi 20 avril 2019

How to convert checkbox list to bits in byte?

I need convert checkbox list of 8 components into single byte, how do it simple?




Retaining CheckBox state within RecyclerView which is feed by SQL Database

Good evening everyone

Brief overview before a greater explanation. I currently have a SQL database which feeds into an arraylist thanks to a modal, we then feed this arraylist to our recycle view adapter which then populates the row.

Now i'm trying to build in the option for the user to select a row and then a check becomes true and tick is displayed. As you all currently know if the state is not stored then it start moving to random rows or being removed completely.

Lets start at the beginning with my SQL Lite database. Three simple rows Title , Description and checkbox state. Note that when a new row is added to the sql he checkbox column is automatically set to false.

Snippet below of the SQL query used to populate my recyclerView adapter

ArrayList<NoteInfoModal> noteInfoModalArrayList = new ArrayList<>();
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    Cursor cursor =  sqLiteDatabase.rawQuery("SELECT * FROM " + Primary_Table + " ORDER BY Col_DateOrder ASC",   null);
    cursor.moveToFirst();


    while (!cursor.isAfterLast()){

        NoteInfoModal noteInfoModal = new NoteInfoModal();
        noteInfoModal.setNoteName(cursor.getString(cursor.getColumnIndex(Col_NoteTitle)));

Applying it to the adapter

homeScreenAdapter = new HomeScreenAdapter(getContext(), primaryDatabase.populateHomeScreenOldestFirst(), filterOption, HomeScreenFragment.this);

Finally binding the information inside the adapter to the correct view (This one is for the check box)

((CustomViewHolder) holder).chkNote.setChecked(Boolean.valueOf(noteInfoModal.noteCheckBox));

Now I understand that I could simply update the row of the SQL DB to be true as this will then save the state, but if the user closes and then opens the app again I want them all to unchecked / false each time

Just looking for another way of approaching this issue.

Thank you




Uncheck other checkbox on checked flutter

I have three checkboxes (lets the user chose different difficulty). Right now the checkboxes are all clickable.

But for obvious reason I only want the user to be able to chose one difficulty at the time- why I'm trying to get every other box unchecked for every new click.

After the user has chosen the difficulty he will be able to make another choice. When that choice is made he will automatically be directed to an other page. (In other words- the checkbox choice is unimportant until the user makes his second choice).

I tried something like

void checkBoxes() {
    if (_value1 = true) {
      _value2 = false;
      _value3 = false;
    } else if (_value2 = true) {
      _value1 = false;
      _value3 = false;
    } else if (_value3 = true) {
      _value1 = false;
      _value2 = false;
    }
  }

But no luck.




vendredi 19 avril 2019

creating a checkbox with t list item and add to collections

Hi i am trying to create a checkbox list from database table for example i have number of options of Drinks and salads i want to let user select the item and specify the quantity and both values should be add in collections.

Please check image of sample check box

https://drive.google.com/open?id=1_8WtTgYjgC8ySiNZWNgzouIlUE6zgj2L

Scenario

Source of Checkbox list is a Table For example check box Label will be Come from table but quantity will be specified on runtime to save in collections.

If i create using htp.p by checkbox tag then it will be definitely rendered on run time how i would access the values of both to add as member in collection




How to get value or id from dynamically populated checkbox using ng-repeat of group by (key,value) if it checked to json array or object

I ma populating channel name from using json object, which included channel name id and price with associated checkbox. When user checked checkbox it should fetch or store selected/checked checkbox id,name,value to be store in json array or object or model.

I have tried checklist-model="request.myChannel" checklist-value="item.channelID"

<!--Showing List of Channels with filter which are applying from multiple DropDownList and one search box -->
         <div ng-repeat="(key, value) in content | filter:searchGenre.Genre | filter:searchLanguage.Language | filter:searchText4 | groupBy: 'Genre'">
            <div class="col-lg-12 bouquet-rupee" style=" padding-left:4px; display:inline-block;" >
                <h5 style="border-bottom:1px solid #ccc;margin-top:15px;">
                <!-- showing Group name and its count eg. News(15) or Movies(25)-->
                 ()
                </h5>
            </div>

                <!-- showing channel details as name and its price -->
                <div class="col-xs-1 col-sm-3" style="border:0px solid #ccc;padding:4px;display:inline-block;" ng-repeat="x in value">
                        <div class=" col-sm-12 card card-body bottom-margin-none " style= "display:inline-block; min-height:; text-align:center; margin:0px; border-radius:3px;padding:8px">
                        <div style="height:45px">
                        <h5 class="" style="display:inline"></h5>
                        </div>
                        <div class="col-lg-12 align-items-center justify-content-between" style="background:;">
                            <h5 class="bouquet-rupee" style="text-align:center;" >
                                <i class="fa fa-inr"></i> Rs.  / month</h5>
                                <!-- wants to get its key and id i.e (Genre and ID) from selected checkbox to json array or object later can be display-->

                                <input id="checkboxCustom2"  type="checkbox" value="" class="checkbox-template">

                          </div>
                        </div>
                </div>
            </div>




How can I select all and deselect all in a nested form array?

I have dynamic formArrays inside dynamic formArrays: A formArray of courses where each course has a formArray of students.

Course_Student List

ngOnInit() {
        this.assignForm = this.fb.group({
            courses: this.fb.array([])
        });

        this.setCourses();
    }

The forms are built from the data, this.courses, which is retrieved from the server.

setCourses() {
        const control = <FormArray>this.assignForm.controls.courses;
        if (this.courses) {
            this.courses.forEach(course => {
                control.push(
                    this.fb.group({
                        courseAssign: false,
                        courseDueDate: "dueDate",
                        students: this.setStudents(course)
                    })
                );
            });
        }
    }

setStudents(course) {
        const studentArray = new FormArray([]);
        course.students.forEach(student => {
            studentArray.push(
                this.fb.group({
                    studentAssign: false,
                    studentDueDate: "dueDate"
                })
            );
        });
        return studentArray;
    }

Here is my HTML:

<form [formGroup]="assignForm" (ngSubmit)="onSubmit()">
    <div fxLayout="row" fxLayoutAlign="end center" class="assign-btn-container">
        <button
            mat-raised-button
            color="primary"
            type="submit">
            Assign
        </button>
    </div>

    <div formArrayName="courses">
        <mat-expansion-panel
            #expPanel
            *ngFor="let course of courses; let i = index"
            [formGroupName]="i">
            <mat-expansion-panel-header>
                <div class="panel-header-text">
                    <div class="course-name">
                            
                    </div>

                    <div class="course-opts">
                        <!-- Course Assign -->
                        <div fxFlex>
                            <mat-checkbox
                                formControlName="courseAssign"
                                (click)="$event.stopPropagation()"
                                (change)="$event ? toggleAssignCourse($event, course, i) : null">
                                Assign
                            </mat-checkbox>
                        </div>

                        <!-- Course Due Date/Time -->
                        <div fxFlex>
                            <input type="text"
                                placeholder="Due Date & Time"
                                formControlName="courseDueDate"/>
                        </div>
                    </div>
                </div>
            </mat-expansion-panel-header>

            <div formArrayName="students">
                <div
                    *ngFor="let student of course.students; let s = index"
                    [formGroupName]="s">
                    <div class="student-name">
                         
                    </div>

                    <mat-action-row class="assignment-opts">
                        <!-- Student Assign -->
                        <div fxFlex>
                            <mat-checkbox
                                formControlName="studentAssign"
                                (change)="toggleAssignStudent($event, course, student, s)">
                                Assign
                            </mat-checkbox>
                        </div>

                        <!-- Student Due Date/Time -->
                        <div fxFlex>
                            <input type="text"
                                placeholder="Due Date & Time"
                                formControlName="studentDueDate"/>
                        </div>
                    </mat-action-row>
                </div>
            </div>
        </mat-expansion-panel>
    </div>
</form>

In the HTML, a course Assign checkbox triggers toggleAssignCourse. And in my class, I tried:

toggleAssignCourse(event, course: Course, i) {
        this.assignForm.value.courses[i].students.map(student => {
            student.studentAssign = true;
        });
    }

This gives the following error: Cannot assign to read only property 'studentAssign' Beyond this attempt, I have tried several other things--too many to list and probably horrible ideas. :(

When a user clicks on the course Assign checkbox, I'm trying to figure out how to select all the students in that course if none or only some students are selected. If the course Assign checkbox is clicked again, all students are deselected.

Any help with this is gratefully appreciated! Thank you in advance.




Multiple checkboxes with Ajax strange behavior

I have a form with many checkboxes, and a PHP page is called for updating the database on each click.

HTML

<form>
   <input type="checkbox" name="status1" id="event_status1" value="1" >
   <input type="checkbox" name="status2" id="event_status2" value="1" >
   <input type="checkbox" name="status3" id="event_status3" value="1" >
</form>

JQuery

  $('input:checkbox').change(function(e) {
     e.preventDefault();
     var isChecked = $("input:checkbox").is(":checked") ? 1:0; 
     $.ajax({
           type: 'POST',
           url: "admin-ajax.php",
           data: { event_status:$("input:checkbox").attr("id"), status:isChecked},
           success: function (response) {
              console.log(response);
           }
     });        
  });

It works well when I check/uncheck each checkbox individualy.

If I check the 3 boxes, the last I have checked won't send "0" status if I uncheck it but wil always send "1".




How Can I Select All The Check boxes By Click on a button from action bar

Here is my RecyclerView Adapter On Each Item i show a check boxes and a save button before save any item user select a check box and save the item i want user click on a button and all the check boxes are selected and when user click on cancel button all check boxes are unchecked how can i do this

I tried on single check box it work good but for multiple its not work




jeudi 18 avril 2019

Using checkbox as User Input to filter data in Pandas

I have a data frame I would like the user to be able to filter based on the values in a specific column

I was able to create an initial option using user input.

def get_subset(df):
    table = input('\nWhich table? Account or Transactions?\n')
    return df[df['Table'] == table]

But this won't be feasible once I have more values in the Table column. I was hoping to create checkboxes and that would be used to filter the data. Like below:

import ipywidgets as widgets

widgets.Checkbox(
    value=False,
    description= ('account'),
    disabled=False
)

But this gave me one checkbox. I am not able to create this for all values in the table column or to connect it to filter data. Does Pandas have this capability?




Passing information from CheckBoxes

I have a problem, I need to make checkboxes and when clicked button to next page it need to go to next page and pass information from selected checkbox to page number 4. If somebody can give me example or anything else that would be great, thank.




Send data from view to controller using radio buttons/checkboxes

I am trying to change the way our current system is relying heavily on javascript to pass data around when i know it can be done just using asp.net mvc. Essentially i have a few checkboxes and a few radio buttons on a form that i am posting to a database, how would you guys go about sending the data from these inputs back to the controller and then working with those values to store it in a table.

I'm looking to basically store the values of the check boxes and radio buttons in the table.




How do I sort a list of checkboxes by their name?

I have a foreach loop which fills a list with checkboxes from a groupbox. Problem is that they are added in a random order. Since I named them all in an ascending alphabetical order I want to sort them by their Name propery.

I've already tried using .Sort() but it doesn't do anything. Also I tried using a Linq expression DigBoxes = DigBoxes.OrderBy(x => x.Name).ToList();

But it also doesn't do anything...

Here's my code:

GroupBox box = (GroupBox)e.Argument;
            string DigInput = "";
            List<CheckBox> DigBoxes = new List<CheckBox>();

            foreach (Control c in box.Controls)
            {
                if(c is CheckBox)
                {
                    DigBoxes.Add(c as CheckBox);
                }
            }




What is the proper ember.js-way to react to a changing checkbox

I have a checkbox like this:



When I click the checkbox the property is changed. Now I like to call a function to persist the property. But what is the best way to do this?

  1. I could bind an observer to property, but this is consindered bad.
  2. I could bind an action to input oder click.

    
    
    

    This doesn't work because the property has still the old value when the action is called.

  3. Extending the class Checkbox:

    import Checkbox from '@ember/component/checkbox';
    Checkbox.reopen({
        onChange: null,
        change() {
            this._super();
            if (this.onChange) this.onChange();
        }
    });
    ...
    
    
    

    But the function change is not documented, even though the source code indicates that it is feasable to override.

  4. I could bind an action to didUpdate or didUpdateAttrs, but the action is called twice. In my case this wouldn't be a problem, because the property is part of a model, so I could call model.get('hasDirtyAttributes') in the action.

So what is the proper ember.js-way to do this?




Do I list the incoming data as a checkbox?

I'm pulling the data, but when I try to checkbox as a list. 'TypeError: Cannot read property 'map' of undefined' is the reason I'm getting this error?

I get the error 'this.state.action.map((action) => { return ()})' in place.

     Console.log(data) : 
            (5) [{…}, {…}, {…}, {…}, {…}]
               0: {id: "816f4329-b74b-4a3b-b3c3-b81fec6f51a1", 
                actiontype: "Called & VM"}
               1: {id: "074979a4-6e4b-4bfc-8971-6898f9fd0127", 
                 actiontype: "Keep an Eye"}
               2: {id: "2e158344-39ca-46ce-a3fa-9d96d039194d", 
                 actiontype: "Follow Up"}
               3: {id: "81eed538-ccb5-4f5f-99f6-3531dc7941b6", 
                 actiontype: "Uninstall"}
               4: {id: "1e21f4af-c009-4897-96ad-33d3caacddc0", 
                 actiontype: "Emailed"}
               length: 5
               __proto__: Array(0)

     Code:  
          state = {
            action: [],
          }
          render() {
             this.state.action = this.props.ActionType.items
          return (

             <div className='popupAddAction'>
                <h1> Check and Uncheck All Example </h1>
                  <ul>
                {
                    this.state.action.map((action) => {
                        return (<CheckBox {...action} />)
                    })
                } 
               </ul> 
            </div>

      Checkbox Component:
           const CheckBox = props => {
             return (
                <li>
             <input key={props.id} type="checkbox" 
               value={props.actiontype} /> 
              {props.actiontype}
                </li>
             )
           }




mercredi 17 avril 2019

I am creating a checkbox list with react-native-elements. How do I check only one box at a time?

I am making a list of check boxes but when I press on one checkbox, it checks all of the checkboxes. I want to select one at a time.

I tried the sample code from react-native-elements 1.1.0 documentation as well as examples from other people but I cannot find the solution.

constructor() {
    super();

    this.state = {
      checked: false,
    };
  }

render() {
    return (
      <View style={styles.container}>
        <ScrollView>
          <CheckBox
            checkedIcon='dot-circle-o'
            uncheckedIcon='circle-o'
            title='checkbox 1'
            checkedColor='red'
            checked={this.state.checked}
            onPress={() => this.setState({ checked: !this.state.checked })}
          />
          <CheckBox
            checkedIcon='dot-circle-o'
            uncheckedIcon='circle-o'
            title='checkbox 2'
            checkedColor='red'
            checked={this.state.checked}
            onPress={() => this.setState({ checked: !this.state.checked })}
          />
        </ScrollView>
      </View>
    );
  }
}

I want to select one checkbox at a time (select the checkbox that I pressed on instead of selecting all at once).




How to make RSelenium avoid an "ok box" before a pdf visualiser when document is not available?

I am using RSelenium to download pdf documents from a database. Some of the documents are available, but, in some cases, the repository is not correct, and a box informing the problem appears (see http://imagem.camara.gov.br/dc_20b.asp?selCodColecaoCsv=D&Datain=16/5/1913#/). It is in Portuguese, and the message says that an error occurred).

I have already tried to identify some characteristics of the box via remDr$findElements(using="class name","modal-content"), but, when the the file link is not broken, the code takes too long to respond and returns the following error message:

Error:   Summary: NoSuchElement
         Detail: An element could not be located on the page using the given search parameters.
         class: org.openqa.selenium.NoSuchElementException
         Further Details: run errorDetails method

My code probably is not much efficient, but, according to other answers, would be effective. The source of problems lies in the third line.

for(link in links){
  remDr$navigate(link)
    if(length(remDr$findElements(using="class name","modal-content"))==0){ 
      botao<-remDr$findElement(using="id","download")
      botao$clickElement()
     }
  }

Probably, there are also other ways to download the pdf using Firefox, but this is enough for what I need.




How to add a Checkbox property for Spring form

I've been building a Spring MVC application that uses SpringDataJPA and hibernate, and leverages MySQL. From some point on I am getting an NumberFormatException for a specific form on my main web-page (named 'main'), which I wasn't able to get rid of. Can you show me where my code went wrong?

Main.JSP

            <spring:bind path="sid">
                <tr>
                    <label for="sid">Choose Preferred Scholar:</label>
                    <c:forEach items="${scholarList}" var="scholar">
                        <td><form:checkbox path="sid" id="${scholar.id}" label="${scholar.fname}" value="${scholar.id}" /></td>
                    </c:forEach>
                </tr>
            </spring:bind>

Stack Trace

org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet [jsp] threw exception
java.lang.NumberFormatException: For input string: "id"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at javax.el.ArrayELResolver.coerce(ArrayELResolver.java:144)
    at javax.el.ArrayELResolver.getValue(ArrayELResolver.java:61)
    at org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:113)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:190)
    at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:701)
    at org.apache.jsp.WEB_002dINF.views.main_jsp._jspx_meth_form_005fcheckbox_005f0(main_jsp.java:1214)
    at org.apache.jsp.WEB_002dINF.views.main_jsp._jspx_meth_c_005fforEach_005f2(main_jsp.java:1174)
    at org.apache.jsp.WEB_002dINF.views.main_jsp._jspService(main_jsp.java:350)

Controller

@RequestMapping(value = { "/main" }, method = RequestMethod.GET)
    public String welcome(Model model) {
        model.addAttribute("addProject", new Projects());
        model.addAttribute("projectList", projectService.getAllProjects());
        model.addAttribute("availableProjectList", projectService.getAvailableProjects());
        model.addAttribute("scholarList", userService.getScholars());
        model.addAttribute("technologiesList", techService.getAllTechnologies());

        return "main";
    }

Service

@SuppressWarnings("unchecked")
    @Override
    @Transactional
    public List<User> getScholars() {
        return entityManager.createNativeQuery("select * from User").getResultList();
    }

User Entity

package com.ajwt.entities;
// Generated 17 באפר׳ 2019, 2:45:49 by Hibernate Tools 4.3.5.Final

import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * User generated by hbm2java
 */
@Entity
@Table(name = "user", catalog = "ajwt")
public class User implements java.io.Serializable {

    private Integer id;
    private String username;
    private String email;
    private String password;
    private String passwordConfirm;
    public String getPasswordConfirm() {
        return passwordConfirm;
    }

    public void setPasswordConfirm(String confirmPassword) {
        this.passwordConfirm = confirmPassword;
    }

    private Date createTime;
    private String fname;
    private String lname;
    private Set<Roles> roleses = new HashSet<Roles>(0);
    private Set<Projects> projectses = new HashSet<Projects>(0);
    private Projects projects;

    public User() {
    }

    public User(String username, String email, String password, String fname, String lname) {
        this.username = username;
        this.email = email;
        this.password = password;
        this.fname = fname;
        this.lname = lname;
    }

    public User(String username, String email, String password, Date createTime, String fname, String lname,
            Set<Roles> roleses, Set<Projects> projectses, Projects projects) {
        this.username = username;
        this.email = email;
        this.password = password;
        this.createTime = createTime;
        this.fname = fname;
        this.lname = lname;
        this.roleses = roleses;
        this.projectses = projectses;
        this.projects = projects;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)

    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name = "username", nullable = false, length = 16)
    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Column(name = "email", nullable = false)
    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Column(name = "password", nullable = false)
    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "create_time", length = 26)
    public Date getCreateTime() {
        return this.createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Column(name = "fname", nullable = false, length = 45)
    public String getFname() {
        return this.fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    @Column(name = "lname", nullable = false, length = 45)
    public String getLname() {
        return this.lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "user_role", catalog = "ajwt", joinColumns = {
            @JoinColumn(name = "uid", nullable = false, updatable = false) }, inverseJoinColumns = {
                    @JoinColumn(name = "rid", nullable = false, updatable = false) })
    public Set<Roles> getRoleses() {
        return this.roleses;
    }

    public void setRoleses(Set<Roles> roleses) {
        this.roleses = roleses;
    }

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "participating_students", catalog = "ajwt", joinColumns = {
            @JoinColumn(name = "usid", nullable = false, updatable = false) }, inverseJoinColumns = {
                    @JoinColumn(name = "pid", nullable = false, updatable = false) })
    public Set<Projects> getProjectses() {
        return this.projectses;
    }

    public void setProjectses(Set<Projects> projectses) {
        this.projectses = projectses;
    }

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "user")
    public Projects getProjects() {
        return this.projects;
    }

    public void setProjects(Projects projects) {
        this.projects = projects;
    }

}




How to store all checked items from a list into the local storage. (Javascript)

I have a list whit a dynamically created checkbox inputs and when the list is done and you finish using it, I want to store the checked items from the list to the localstorage.

HTML: ...

(also y have a kind of dialog where you create the new checkbox items and appends them to the list) ...

Js:

function add_checkbox_item(){

var product = document.getElementById('addirp').value;
var text_product = document.createTextNode(product);
var checkbox_product = document.createElement('ons-checkbox')
checkbox_product.appendChild(text_product);
var finall_product = document.createElement('ons-list-item');
finall_product.appendChild(checkbox_product);
    finall_product.classList.add("products");

document.getElementById('productos').appendChild(finall_product);

    dialog = document.getElementById('dialog1'); 
dialog.hide();  

}; 

function savefunction(){ HERE IS WHERE I START GETTING LOST

var checkedValue = null; 
var inputElements = document.getElementsByClassName('products');
for(var i=0; inputElements[i]; ++i){
  if(inputElements[i].checked){
       checkedValue = inputElements[i].value;
       break;


  }}}




How to instigate action when input is checked in SCSS?

Its very simply and I have looked at all these examples but still am not able to figure out what I am doing wrong!

I have created a custom checkbox, increased the size and style, and when it is clicked I want the letter "A" to appear in the box, but it simply will not respond, maybe a second pair of eyes will help me identify the problem.

below is my html and css:

           .container {
                position: relative;
                cursor: pointer;
                display: block;

                input,
                label {
                    display: inline-block;
                }

                input {
                    // opacity: 0;
                    position: absolute;
                    height: unset;
                    width: unset;
                    cursor: pointer;
                }

                label::before {
                    border: 1px solid #333;
                    content: "";
                    display: inline-block;
                    font: 16px/1em sans-serif;
                    height: 50px;
                    margin: 0 .25em 0 0;
                    padding: 0;
                    vertical-align: top;
                    width: 50px;
                    border-radius: 5px;
                    color: red;
                    font-size: 50px;
                    padding: 10px;
                }
            input[type="checkbox"]:checked + label::before {
                content: "A"; //code for checked
             }
             
            }
<div class="container">
<div>
<label for="form_agreeTerms" class="required">Agree terms</label>
<input type="checkbox" id="form_agreeTerms" name="form[agreeTerms]" required="required" value="1">          
</div>
</div>

here it is in codepen