jeudi 31 décembre 2015

How to get total price if the user has checked multiple checkboxes?

The title might not seem clear but this is my problem.

A user can check either 1 or 2 checkboxes. When the checkbox is checked, it asks for the quantity. enter image description here

What if the user clicks both checkboxes, how can I get the total price?

The checkbox values are saved in multiple rows in MySql. The number 57 in DocumentRequest_idDocumentRequest is a foreign key from another table which means it came from the same user. Also, I want the price column for both rows to yield the same value which is 40. The value of 40 is from 30 + 10 which is evident in the column isPartOfTotal. But is shows 10 and 40, respectively. Something is wrong with my calculation/code.

enter image description here

This is my php code:

<?php
include 'config.php';

if (isset($_POST['documentRequest1']))
    {
        $chkbox = $_POST['docs'];
        $id = $_POST['a'];
        $totalPrice = 0;

        foreach($chkbox as $chk1)  
            { 
                if($chk1=='Certificate of Residency') 
                    {
                        $chek_val=$_POST['d1'];

                    }
                else if($chk1=='Barangay Clearance') 
                    {
                        $chek_val=$_POST['d2'];
                    } 

                $result = mysqli_query($conn, "SELECT price FROM document WHERE typeOfDoc = '$chk1';");
                $row = mysqli_fetch_assoc($result);
                $isPartOfTotal = $chek_val * $row["price"];
                $totalPrice = $totalPrice + $isPartOfTotal; //corresponds to the price column in the table.

                $sql = mysqli_query($conn, "INSERT into requestitem (DocumentRequest_idDocumentRequest, Document_idDocument, quantity, isPartOfTotal, price) VALUES ((SELECT idDocumentRequest FROM documentrequest WHERE Person_idPerson = '$id'), (SELECT idDocument FROM document WHERE typeOfDoc = '$chk1'), '$chek_val', '$isPartOfTotal', '$totalPrice');");
            } 

        echo "You have succesfully submitted a new record.";
        mysqli_close($conn);    
    }                               
?>

I hope I explained it clearly. Please help me. Thank you so much.




How to make multiple checkboxes work with php and sql

How would I pass an array of multiple checkboxes and values through php, saving to a sql database, as well as being able to pull up the saved data back on the client side?

For example, I have an array that saves checkbox values in the way of '"checked"""checked""""', but not only do I want to save the checked value, I also want to save the form data, as follows :

  • Apples : Checked
  • Oranges : Not Checked
  • Bananas : Checked
  • Tomatoes : Checked

Any help would be GREATLY appreciated, please answer with context of how to do, not just code - still learning!

Here is the code I have so far :

(index page)

    <?php
                $salesman = json_decode($invoice['Invoice']['salesman'], true);
                    if(empty($salesman)){
                    for($i = 1; $i <= 5; $i++){
                    echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'"/> '.$i.'<br>';
                    }
                    } else {
                    foreach($salesman as $k => $v){
                    $i = $k+1;
                    if($v == "checked") {
                    echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" checked/> '.$i.'<br>'; // if checked, check.
                    } else {
                    echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'"/> '.$i.'<br>'; // if not checked, don't check.
                    }
                }
            }
            ?>

(php page)

$salesman = $data['data-invoice-salesman']; // this is an array
                $salesman_array = array(); // create new array
                for($i = 1; $i <= 5; $i++){ // loop from 1 to 5
                if(in_array($i, $salesman)){ // if value exists (has been selected), stack 'checked', if not, stack ''.
                    $salesman_array[] = "checked";
                } else {
                    $salesman_array[] = "";
                }
                }
                $salesman_json = mysqli_real_escape_string($this->_con, json_encode($salesman_array)); // encode the array into JSON and then escape it.




HTML Form data from checkboxes within while loop

I have a really basic Date system on a site which displays the dates from the Database using a While loop, next to each date that is listed is a check box.

I would like the user to be able to select as many dates as they would like and click submit to remove these dates or edit these dates.

I am having trouble figuring out how I would get the data from multiple check-boxes using only one within the while loop which could be used multiple times?

Here is my current code:

<form action="" method="post">
<b>Current Dates:</b> <button type="submit" id="remove_dates" name="remove_dates" class="btn btn-danger btn-sm">Remove Selected</button> 
<hr> 
<div style="overflow-y: scroll;height:100px">
<?
$sqldate = "SELECT * FROM `foiu51r_calendar` ORDER BY date DESC";
$resultdate = $conn->query($sqldate);

if ($resultdate->num_rows > 0) {
// output data of each row
while($rowdate = $resultdate->fetch_assoc()) {
$date_id = $rowdate['date_id'];
$dates = $rowdate['date'];

?>
<input type="checkbox" id="date_id" name="date_id" value="<? echo $date_id; ?>"> <b><? echo date("d/m/Y", strtotime($dates)); ?></b><br>
<?
    }
    }
?>
</div>
</form> 

if(isset($_POST['remove_dates'])){
    $date_id = $_POST['date_id'];
}




database update using switchery switch using ajax in codeigniter

I am developing an attendance management codeigniter app and i am using switchery switch plugin to update attendance status. so the process will be:

  1. system display the list of student with attendance status in checkbox with switchery plugin
  2. using check or uncheck the checkbox with switchery plugin, if the student is present or absent or simply user change the status.
  3. system sends the form using ajax, if the student present 1 or absent 0, with student ID and attendance date
  4. and simply system will change the attendance status of student
  5. NOTE* THE VALUE OF $date $month $year $program_id $batch_id and $section_id is loaded before in controller function parameter.

and this my app's preview... i need to this form working using ajax preview of attendance app with switchery plugin

and this is my code for the view.

<!-- student attendence status update form -->
<form method="post" action="<?php echo base_url();?>index.php?admin/student_attendance/<?php echo $date.'/'.$month.'/'.$year.'/'.$program_id.'/'.$batch_id;?>">
  <!-- start datatable -->
  <table class="table table-hover dataTable table-striped width-full" id="departmentTableTools">
    <thead>
      <tr>
        <th class="text-center"><?php echo get_phrase('rool'); ?></th>
        <th class="text-center"><?php echo get_phrase('name'); ?></th>
        <th class="text-center"><?php echo get_phrase('status'); ?></th>
      </tr>
    </thead>
    <tbody>
      <?php $students = $this->db->select('*')
->from('student as tbl1, student_acedemic_process as tbl2')
->where('tbl1.student_id = tbl2.student_id')
->where('tbl2.program_id ='.$program_id)
->where('tbl2.batch_id ='.$batch_id)
->where('tbl2.status = 1')
->get()->result_array();
foreach($students as $row):?>
      <tr>
        <td class="text-center"><?php echo $row['roll_no'];?></td>
        <td class="text-center"><?php echo $row['name'];?></td>
        <td class="text-center">
          <?php 
//inserting blank data for students attendance if unavailable
$verify_data  = array(  'student_id' => $row['student_id'],
'date' => $full_date);
$query = $this->db->get_where('attendance' , $verify_data);
if($query->num_rows() < 1)
$this->db->insert('attendance' , $verify_data);

//showing the attendance status editing option
$attendance = $this->db->get_where('attendance' , $verify_data)->row();
$status   = $attendance->status;
?>

<input type="checkbox" value="1" id="inputBasicOn" name="status_<?php echo $row['student_id'];?>" 
data-plugin="switchery" <?php if($status == 1) echo 'checked'; ?> />
        </td>
      </tr>
      <?php endforeach;?>
    </tbody>
  </table>
  <input type="hidden" name="date" value="<?php echo $full_date;?>" />
  <center>
    <input type="submit" class="btn btn-info" value="save changes">
  </center>
</form>

and this my controller code to update the database

if($_POST)
{
// Loop all the students of $program_id, $batch_id, $section_id

$students = $this->db->select('*')
->from('student as tbl1, student_acedemic_process as tbl2')
->where('tbl1.student_id = tbl2.student_id')
->where('tbl2.program_id ='.$program_id)
->where('tbl2.batch_id ='.$batch_id)
//if(!empty($section_id)){
->where('tbl2.section_id ='.$section_id) 
//}
->where('tbl2.status = 1')
->get()->result_array();

foreach ($students as $row)
{

if(isset($_POST['status'.$row['student_id']])){
$attendance_status  =   $this->input->post('status_' . $row['student_id']);
}

$this->db->where('student_id' , $row['student_id']);
$this->db->where('date' , $this->input->post('date'));

$this->db->update('attendance' , array('status' => $attendance_status));
}

$this->session->set_flashdata('flash_message' , get_phrase('data_updated'));
redirect(base_url() . 'index.php?admin/student_attendance/'.$date.'/'.$month.'/'.$year.'/'.$program_id.'/'.$batch_id , 'refresh');



mercredi 30 décembre 2015

checkbox validation in symfony2

I am creating a registration form in symfony2. I need to validate this checkbox, if a user has not checked this checkbox then there should be a client side validation.i have used client side validation also but it is not validating it.
This is my registration form type.

$builder->add('check', 'checkbox', array(
                    'label'     => 'I agree to terms and conditions',
                    'required'  => false,
                    'mapped' => false,
                    'value'=>false,
                    'translation_domain' => 'FOSUserBundle'));

This is my CLient side java script

var check = $("#fos_user_registration_form_check").val();
                    if(check!=1)
                    {
                        $("#msgCheck").html('Check the Box').css('color','red').show();
                        $error=true;
                    }else{
                        $("#msgCheck").hide();
                        $error=false;
                    }




How to store multiple checkbox value in one column database?

I want to store checkbox value to one column info database and set it NULL for table user

Here is my code for checkbox:

<tr valign="top">
<td class="label">How did you hear about our journal?</td>
<td class="value">
<input type="checkbox" name="Info[]" id="Info" value="Advertisement"/> <label for="Info">Advertisement</label><br />
<input type="checkbox" name="Info[]" id="Info" value="Colleagues" /> <label for="Info">Colleagues</label><br />
<input type="checkbox" name="Info[]" id="Info" value="Conferences" /> <label for="Info">Conferences</label><br />
<input type="checkbox" name="Info[]" id="Info" value="Friends" /> <label for="Info">Friends</label><br />
<input type="checkbox" name="Info[]" id="Info" value="Journal Website" /> <label for="Info">Journal Website</label><br />
<input type="checkbox" name="Info[]" id="Info" value="News" /> <label for="Info">News</label><br />
<input type="checkbox" name="Info[]" id="Info" value="Search Engine"/> <label for="Info">Search Engine</label><br />
<input type="checkbox" name="Info[]" id="Info" value="Twitter" /> <label for="Info">Twitter</label><br />
<input type="checkbox" name="Info[]" id="Info" value="Others"/> <label for="Info">Others</label><br />

</td>
</tr>

output

and code to store checkbox value:

/**
 * Get info.
 * @return string
 */
function getInfo() {
    return $this->getData('Info');
}

/**
 * Set Info
 * @param $Info string
 */
function setInfo($Info) {
    $checkbox = implode(",",$this->setData('Info', $Info));
    return $checkbox;
}

/**
 * Internal function to return a User object from a row.
 * @param $row array
 * @return User
 */
function &_returnUserFromRow(&$row) {
    $user = new User();
    $user->setInfo($row['Info']);
    return $user;
}

/**
 * Insert a new user.
 * @param $user User
 */
function insertUser(&$user) {

    $this->update( sprintf('INSERT INTO users
                          (Info)
                          VALUES (?)',

                          array( $user->getInfo() )
                          );

    return $user->getId();
}

and it is return null on database.

null

Is there any steps missing/mistake in my code because I can't figure it out. Please help. Thanks.




Javascript function doesn't work on uncheck the check box

   <html>
    <head>
        <title>Test</title>
<script type="text/javascript" src="http://ift.tt/1EjeICQ"></script>
    </head>
    <body>

    <button id="check_box" onclick="check_box();"> check box </button>
    <br> <br>
    <input type="checkbox" id="checkboxF1" class="css-checkbox"> Test

    <script>
    $('#checkboxF1').on('change', function() {
  alert("test"); 
});

    function check_box(){
        document.getElementById("checkboxF1").checked = true;   
    }

    </script>

    </body>
    </html>

This onchane function work while check the checkbox directly. but it doesn't work when check the checkbox through a function ie function name check_box(). i want to work the onchange function while check the checkbox even it check through a function( 'check_box()' ).




How to require a checkbox be checked in ASP.Net using Formvalidation.io and Bootstrap

This should be easy, but I've yet to arrive at a solution. I'm using

  • ASP.Net Ajax
  • Bootstrap 3.3
  • Formvalidation.io v0.7.0

I have a single check box that the user has to check before the form can be submitted. The following doesn't work. (I have other validation on the page that does work, so it's not the set up of Formvalidation.io)

Any suggestions appreciated!

<div class="row form-group">
  <div class="col-lg-3 col-md-4 col-sm-4 col-xs-4 right padLabel">
  </div>
  <div class="col-lg-6 col-md-4 col-sm-4 col-xs-4">
    <label class="control-label">
      <asp:CheckBox ID="chkRelease" runat="server" Text="Yes, I agree" data-fv-notempty="true" data-fv-notempty-message="Release is required" />
    </label>
  </div>
  <div class="col-lg-3 col-md-4 col-sm-4 col-xs-4">
  </div>
</div>



Jquery .change can't retrieve inserted checkbox values

I have a serious problem in my script when I want to add a new checkbox input through ajax call. The problem is that i can't retrieve the value of this checkbox after it's inserted.

I give an example here in jsfiddle : http://ift.tt/1OlsiPA

Script Code :

<script>
    $(function() {
      $(".ch").change(function() {
        // Récupérer les données du formulaire
        var country = $("select#country").val();

        var op = "<td>Options :</td>" +
          "<br />" +
          "<td>" +
          "<div>" +
          "<label>" +
          "<input type='checkbox' class='ch' id='option1' name='options' class='ch' value='1'>Option1</label>" +
          "</div>" +
          "<div>" +
          "<label>" +
          "<input type='checkbox' id='option2' name='options' class='ch' value='2'>Option2</label>" +
          "</div>" +
          "</td>";

        if (country != "") {
              $('#options_insert').html(op);
        }
        var options = $("input[name=options]:checked").map(function() {
          return this.value;
        }).get().join(",");

      alert("Country=" + country + " options=" + options);

      });

    });
</script>

Html Code :

<table>
  <tr>
    <td>
      Selection :
    </td>
    <td>
      <select name="select" class="ch" id="country">
        <option value="">Nothing</option>
        <option value="val1">Maroc</option>
        <option value="val2">USA</option>
        <option value="val3">Egypt</option>
      </select>
    </td>
  </tr>
  <tr id="options_insert">

  </tr>
</table>

any help will be very apreciated




How to hide and show rows in datatable with a checkbox

I have a datatable as follows:

<table id="dt_default" class="uk-table exclude_table" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Number</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr class="aa">
            <td>1</td>
            <td>N1</td>
        </tr>
        <tr class="bb">
            <td>1</td>
            <td>N1</td>
        </tr>
        <tr class="cc">
            <td>1</td>
            <td>N1</td>
        </tr>
        <tr class="dd">
            <td>1</td>
            <td>N1</td>
        </tr>
    </tbody>
</table>

I have a set of checkbox as follows, which is placed above the datatable:

<div>
     AA<input type="checkbox" class="exclude" value="aa">
     BB<input type="checkbox" class="exclude" value="analysis">
     CC<input type="checkbox" class="exclude" value="progress">
     DD<input type="checkbox" class="exclude" value="done">
</div>

What I need is: When a checkbox is checked the class corresponding to its value must hide from the table and when it is unchecked, it should show it back.

Eg: If you check the checkbox AA, the value corresponding to it is aa. So class aa must be hidden from table and when it is unchecked, it must show again.

The script I have tried for this is:

$('.exclude').click(function() { 
    $(".exclude").each(function(){
        if ($(this).prop('checked')==true)
        { 
            var hidden = $(this).attr("value");
            $.fn.dataTableExt.afnFiltering.push(
            function( oSettings, aData, iDataIndex ) {
                var row = oSettings.aoData[iDataIndex].nTr;
                return $(row).hasClass(hidden) ? false : true;
            }
            );
         }
        });                  
    });

This code is not working as expected.

What it does is, it hides the corresponding class when a checkbox is checked and then we do either search/sort in datatable. Not directly when the checkbox is checked.

Also how to show the row back when checkbox is unchecked ?




How to select Input checkbox and create automaticaly div in other div

I have an simple form with two checkbox:

<form id="formTest">
        <input type="checkbox" id="imageOne"> <img src="/uploads/imagens/imageone.jpg">
        <input type="checkbox" id="imageTwo"> <img src="/uploads/imagens/imageone.jpg">

</form>  

In jquery

http://ift.tt/1mj84vC

<script>
        $("#formTest").change(function () {       
           $('<div>',{
             id : 'imageTow or One',
           });

        });    
    </script>

How do I to select only one or two or more checkbox and are created divs with images inside the div class = "test"?

Thanks for any help




VBA to Create Check Boxes Using Header Title in Multiple Columns

I'm trying to create multiple checkboxes for a spreadsheet I have that has around 200 columns right now. The plan is for the script to go through the column and create check boxes for each column that has a value in its 4th row (where the header title is currently). I'm still a beginner when it comes to VBA so I'm not sure where to start.

To be specific, the header is located along row 4 and spans across ~200 columns. I'd like the individual check boxes (with caption inherited from text in the header) to be created along a single column (I will rearrange the boxes once they are created) on another worksheet in the same workbook.

Appreciate any help I can get on doing this!




Style checkbox , set background color on checked to 70% inside the window

I could use some help with the styling of my checkbox field. Right now, I made some custom css myself, and it work very well. Now I just need to have a checked mark inside the checkbox window.

Code so far:

    input[type=checkbox] {
    -webkit-appearance: none;
    appearance: none;
    width: 30px; /*Desired width*/
    height: 30px; /*Desired height*/
    cursor: pointer;
    border: 1px solid #CCC;
    border-radius: 2px;
    background-color: #fcfbfb;
    display: inline-block;
    box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.05);
    color: black;
    box-sizing: content-box;
}

input[type="checkbox"]:checked {
    background-color: #002B45;
    border-radius: 2px;
    border: 1px solid #CCC;
    box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.05);
    color: black;
    cursor: pointer;
}

input[type="checkbox"]:focus {
    outline: 0 none;
    border-radius: 2px;
    box-shadow: none;
}

Html code:

 <div class="column small-12">
                            <div class="checkbox">                             
                                @Html.CheckBoxFor(m => m.RememberMe, new { @class = "sbw_checkbox" })
                                @Html.LabelFor(m => m.RememberMe, new { @class = "sbw_label" })
                            </div>  
                        </div>

Have made some pictures so you can see how it looks.. and what I'm trying to achive.

This is when its not checked.

Not checked

This is when its checked.

enter image description here

This is what I'm trying to create.

enter image description here

Can any see, or have something I can try?




I have a listview with checkboxes and i filter the listview values and checked a values after filtering checkbox

I have a listview with checkboxes and I filter the listview values and checked a values after filtering checkbox checking positions will be change. How can I solve this problem?




jQuery run function onchange as on/off state and not repeat itself

I have multiple checkboxes running onchange="calculatetotal()". Then I have a function for each of these checkboxes that adds/removes a row to the first empty row in the table. The problem is that since everytime a checkbox is clicked the total is calculated, when a row has been added by another checkbox, its added for a second time. How can I make each checkbox add its row only once and at the same time keep updating the total?

    calculatetotal = function () {
        var total = applecalc() + orangecalc() + pearcalc();
        alert(total);  
    }

    function applecalc() {
      var price = 0;
      var btn = $('#chkbx');
      var firstemptyrow = $('#tableid tr:empty:eq(0)');
      var removepreviousrow = $('.xxx');

      if (btn.is(':checked')) {
        price = 3;
        firstemptyrow.append('<td class="xxx">apple</td><td class="xxx">$3</td>');
      } else {
        price = 0;            
        removepreviousrow.remove();
      }
      return price;
    }




mardi 29 décembre 2015

Get values of selected checkboxes and their associated textareas in Javascript

I have a HTML form. In this form I have 5 checkboxes and each checkbox has an associated textarea. So I want to get the values of only the checked checkboxes and their associated textarea text. I am able to get the values of the checked checkboxes but I can't figure out a way to get the values of their associated textarea.

My HTML code is:

<form class="my-form" id="id_MyForm">

<div class="form-group">
  <label class="qquestion">6. Which of the following is most relevant to you and why? (Select all that apply).</label>
    <div class="checkbox" id="id_Question6">
  <label>
    <input type="checkbox" id="input_que6a" value="Time" name="question6" />Time
  </label>
  <textarea name="question6a_textarea" id="id_que6a" class="form-control" placeholder="Please provide the reason"></textarea>
  <br>

  <label>
    <input type="checkbox" id="input_que6b" value="Money" name="question6" /> Money
  </label>
  <textarea name="question6b_textarea" id="id_que6b" class="form-control" placeholder="Please provide the reason"></textarea>
  <br>

  <label>
    <input type="checkbox" id="input_que6c" value="Family" name="question6" /> Family
  </label>
  <textarea name="question6c_textarea" id="id_que6c" class="form-control" placeholder="Please provide the reason"></textarea>
  <br>

  <label>
    <input type="checkbox" id="input_que6d" value="Hobbies" name="question6" /> Hobbies
  </label>
  <textarea name="question6d_textarea" id="id_que6d" class="form-control" placeholder="Please provide the reason"></textarea>
  <br>

  <label>
    <input type="checkbox" value="Other" name="question6" id="other_que6" /> Other
  </label>
  <br>
  <textarea name="question6_textarea" id="id_Question6_textinput" class="form-control" placeholder="Please elaborate"></textarea>

    </div>
 </div>

  <div class="text-center">
    <button type="button" id="id_SubmitForm" class="btn btn-success">Submit</button>
  </div>
</form>

My JavaScript code is:

/* Latest compiled and minified JavaScript included as External Resource */
var question6AnsArray = [];

/* To hide all the text areas when the page loads */
$("#id_Question6_textinput").hide();
$("#id_q6_opH_textarea").hide();
$('#id_que6a').hide();
$('#id_que6b').hide();
$('#id_que6c').hide();
$('#id_que6d').hide();


 /* To show appropriate text area for selected check box */
 $('#input_que6a').click(function() {
     $("#id_que6a").fadeToggle(this.checked);
 });
 $('#input_que6b').click(function() {
     $("#id_que6b").fadeToggle(this.checked);
 });
 $('#input_que6c').click(function() {
     $("#id_que6c").fadeToggle(this.checked);
 });
 $('#input_que6d').click(function() {
    $("#id_que6d").fadeToggle(this.checked);
 });

 $('#other_que6').click(function() {
    $("#id_Question6_textinput").fadeToggle(this.checked);
 });

$("#id_SubmitForm").click(function() {

  // To get all the selected checkbox values and their associated textareas
  $('input[name="question6"]:checked').each(function() {
    question6AnsArray.push(this.value);

  //Here I want to get the value for the textarea.
  });
    var question6Answer = question6AnsArray.join(", ");
    alert(question6Answer);
});

Here is a link to JSFiddle




multiple checkbox in single column for TbExtendedGridView in yii 1.1

I have used table extended grid viw in my form.I want to add multiple checkboxes in a single column?What is the solution?




How to uncheck all checkboxes except on using jQuery?

I have a form that has multiple checkbox groups.

Each checkbox has a custom html 5 entity called itemtype

When the input of type="checkbox" changes, I need to check checkbox that was just selected. If the value of it's data-itemtype is equal to 'Skipper', I want to uncheck all other checkboxes that belong to the same group except for the one that was last check.

I have create a fiddle to show you what I have done along with the form http://ift.tt/1OYdnqS

I tried to do something like this but is is not working

    var skipper = $("input[name='"+inputName+"']:checkbox[data-itemtype='Skipper']");


    if( skipper.is(":checked")){

        $(this).attr('checked', false);

        skipper.attr('checked', true);

    }

Also, how can I tell the difference the input and the check box?

$(this) seems to be referring to the input it self not to the checkbox "which belongs to the input"

Thank you




Android listview checkbox

I have a listbox where i choose the elements i want to download by a checkbox, and a FloatingActionButton to confirm. The problem is that on my phone(Android 5.0.2) i get a "Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference" On my tablet (Nexus7 Android 6.0) everything work!

        FloatingActionButtonDone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            for (int j = 0; j < ListActivityListView.getCount(); j++) {

                v = ListActivityListView.getChildAt(j);

                //Here im having troubles!
                ck = (CheckBox) v.findViewById(R.id.ListActivityCheckBox);


                if (ck.isChecked()) {

                    /*
                    Stuff to download ++
                    */

                }

            }
            /*
            Here I have the code to download my stuff
            */
        }//End of onClick

    });//End of  FloatingActionButtonDone.setOnClickListener

Where: - ck is a CheckBox ck, declared in my class variables. - ListActivityListView is the ListView inside my activity.

I repeat same code works on my table, but doesn't on my phone. So i have literally no idea. Since my project is composed by 12 classes, i tried to post here the relevant code i'm having trouble with.




Checkboxes in a range

I have a sheet with checkboxes and names. I need one specific cell to show only the value of the cell related to the checkbox. For example.

when I press the checkbox for Lorena the cell A1 shows Lorena, if I check the one for Ricardo the cell A1 must show Ricardo. Is there any way to do it? I need to work with a range of 15 records.

Thank you!




tkinter python checkbox issues

The intent of this python file is to read in a file similar to the one below, modify the lines that have "PL" in the shape field. the issues I am having is the OK box is bleeding into the initial file selection button. Also, the OK button does not show up in the initial checkbox, and will not update the first line with "PL" in it. Once the first checkbox and the file selection box is Xed out, the checkbox seems to work as intended for the second line on. Could someone please help me figure this out? it should bring up the file selection box, select file to open, select file to save as. this box should stay open, and the checkbox should open. once you make your selection, it should open again and again until there are no more lines that have "PL" in them. the new file should have the added data in the correct position.

This is in the read file "1288.kss". Save file as "1288r.kss"

D,88C200a,0,88C200a,88C200a,1,HSS,5x5x.375,A500B,4311.65,,S1E,,,,,,,,,,,,,,,,,,,
W,88C200a,0,COLUMN,07/23/15,SDS7.420,,,,,,,,,,,,,,,,,,,,,,,,,
M,88C200a,1,COLUMN,,,,,,,,,,,,,,,,,,,,,,,,,,,
S,2B,1,,,,,,,,,,,,,,,,,,,,,,,,,,,,
D,88C200a,0,88C200a,bs5_2,1,PL,1-1/4x13,A36,330.2,,,,,,,,,,,,,,,,,,,,,
D,88C200a,0,88C200a,p307,1,PL,3/8x9-5/16,A36,838.2,,,,,,,,,,,,,,,,,,,,,
D,88C200a,0,88C200a,p310,1,PL,3/8x7-1/4,A36,379.41,,,,,,,,,,,,,,,,,,,,,
D,88C200a,0,88C200a,p317,1,PL,3/8x6-5/8,A36,533.4,,,,,,,,,,,,,,,,,,,,,

this is the code:

from Tkinter import *
import Tkinter
import tkFileDialog


def main(root):
     fn = tkFileDialog.askopenfilename(master=root,
                                        initialdir=r'C:\kiss\Routing',
                                        filetypes=[("KSS", "*.kss")])
     if not fn: return
     fnFiltered = tkFileDialog.asksaveasfilename(master=root, 
                    initialdir=r'C:\kiss\Routing', 
                    filetypes=[("KSS", "*.kss")])
     if not fnFiltered: return 

     lines = open(fn).readlines()
     index0 = 0
     indexPage = 1
     index2 = 2
     indexDetail = 3
     # index 4 is the part number
     indexPart = 4
     indexQty = 5
     indexShape = 6 
     indexDescr = 7 
     # index 8 is the grade 
     indexGrade = 8 
     # length index, length is in millimeters - convert to inches and 16ths 
     # with function mm_to_imperial 
     indexLength = 9
     index10 = 10
     # index 11 is the remarks column 
     indexRemark = 11 
     # 1-1/2 | 1 | 15

     '''
     revisions:

     '''

     outputLines = [] 
     for i, line in enumerate(lines): 
          if "," in line or "*" in line: 
               lineList = line.strip().split(",")
               if lineList[0] == "L":
                    continue
               if lineList[0] == "A":
                    continue  
               if lineList[0] == "D":

                    if "PL" in lineList[indexShape]:
                         #
                         pn1 = lineList[indexPart]
                         #
                         def results(): 
                              top.destroy() 

                         top = Tkinter.Tk() 
                         CheckVar1 = Tkinter.IntVar() 
                         CheckVar2 = Tkinter.IntVar() 
                         CheckVar3 = Tkinter.IntVar()
                         CheckVar4 = Tkinter.IntVar()

                         CheckVar1.set(1) 
                         CheckVar2.set(0) 
                         CheckVar3.set(0)
                         CheckVar4.set(0)

                         C1 = Tkinter.Checkbutton(top, text = "Route 25 - Plate Table", 
                                                  variable=CheckVar1, height=1, width=20)
                         C2 = Tkinter.Checkbutton(top, text = "Route 35 - Forming", 
                                                  variable=CheckVar2, height=1, width=20) 
                         C3 = Tkinter.Checkbutton(top, text = "Route 175 - T-Load#1", 
                                                  variable=CheckVar3, height=1, width=20) 
                         C4 = Tkinter.Checkbutton(top, text = "Route 176 - T-Load#2", 
                                                  variable=CheckVar4, height=1, width=20) 
                         C1.pack() 
                         C2.pack() 
                         C3.pack()
                         C4.pack()
                         bt = Button(text='OK', command=lambda: top.destroy()) 
                         bt.pack(side='left') 
                         top.mainloop() 
                         cv1 = CheckVar1.get()
                         cv2 = CheckVar2.get()
                         cv3 = CheckVar3.get()
                         cv4 = CheckVar4.get()

                         #
                         if cv1 == 0:
                              rt1 = ""
                         if cv1 == 1:
                              rt1 = "25"
                         if cv2 == 1:
                              rt1 = rt1+"-35"
                         if cv3 == 1:
                              rt1 = rt1+"-175"                         
                         if cv4 == 1:
                              rt1 = rt1+"-176"

                         lineList[index10] = rt1


               outputLines.append(lineList)


     try: 
          f = open(fnFiltered, 'w') 
          f.write("\n".join([','.join(lineList) for lineList in outputLines])) 
          f.close() 
     except Exception, e: 
          print e 

     # print "\n".join([','.join(lineList) for lineList in outputLines]) 
root = Tkinter.Tk()
Tkinter.Button(root, text="Select File To Process", command=lambda: main(root)).pack()
Tkinter.Button(root, text="Exit", command=root.destroy).pack()
root.mainloop()




DomCrawler Checkbox Checking or Adding new DOM Content

I'm using Symfony2 (and Goutte). I have a page that's old and I need to check a checkbox on the page, but can't find a way to do it. I have scraped the page into a $crawler object and am using different methods from the domcrawler API. Here's the HTML:

<tr>
    <td>
        <input type="checkbox">
        Text Next to Checkbox
    </td>
</tr> 

I've tried so many $crawler-> things, but cannot figure out how to check that checkbox, neither with domcrawler nor goutte. Also, I cannot use $form[]->tick() because this page is terrible in its architecture, and I'm unable to make a $form object.

Any ideas? Thanks!




Sending and receiving checkbox data to and from SQL w/PHP

I am trying to figure out the SQL code that I would need to pass an array of checkbox data to sql, and then pull the same array back out of sql for a form afterwards. I received some help from a friend on how to save the data into an array, but do not know the best practice to pull the array from SQL in the form of checkbox data.

This is what I have so far for my form :

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-default active">Apples
        <input type="checkbox" name="fruit[]" value="Apples" <?= in_array('Apples', $invoice['basket']['fruit']) ? '' : '' ?> autocomplete="off">
    </label>
    <label class="btn btn-default active">Bananas
        <input type="checkbox" name="fruit[]" value="Bananas" <?= in_array('Bananas', $invoice['basket']['fruit']) ? '' : '' ?> autocomplete="off">
    </label>
    <label class="btn btn-default active">Oranges
        <input type="checkbox" name="fruit[]" value="Oranges" <?= in_array('Oranges', $invoice['basket']['fruit']) ? '' : '' ?> autocomplete="off">
    </label>

This is how I can pull NON-ARRAY data, looking for correct code for the array :

$fruit = mysqli_real_escape_string( $this->_con, isset( $basket['fruit']) ? 1 : 0);




Checkbox(es) clicked will show another input field, how to put it in the database?

I have a working code where if I select multiple checkboxes, it will be saved in the database in separate rows (it is required). Also, I have a working code where if it checks a certain checkbox, another input field will show. Now, how do I save the checkbox value along the other input field that comes with it in the database?

This is the form:

<form class="form-horizontal form-label-left" name = "documentRequest" enctype="multipart/form-data" role="form" method="post" novalidate>

<div class = "second">

<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12"> Document Request(s) <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">

<input type="checkbox" name="docs[]" id="doc1" value="Certificate of Residency" /> Certificate of Residency
<br/>
<div class = "col-xs-3">
    <input name="d1" class="form-control col-md-7 col-xs-12" required="required" type="number">
</div>

<div class = "clearfix"></div>

<input type="checkbox" name="docs[]" id="doc2" value="Barangay Clearance"  /> Barangay Clearance                                                    
<br />
<div class = "col-xs-3">
    <input name="d2" class="form-control col-md-7 col-xs-12" required="required" type="number">
</div>

    <div class = "clearfix></div>
</form>

This is my php code (this works; it saves multiple checkbox values):

<?php
include 'config.php';

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

 $chkbox = $_POST['docs'];

 $i = 0;

 foreach($chkbox as $chk1)  
   {  
       $query = mysqli_query($conn, "INSERT INTO document(typeOfDoc) VALUES ('$chk1');"); 
   }  
 echo "Checkbox value is successfully submitted.";
 } ?>

This is the picture of the form: enter image description here

Can you all please help me? How do I save this? Thank you.




Enable a nested in a disabled Jquery mobile Checkbox

I'm using the JQuery Mobile Checkboxradio widget to have a list of checkboxes on a mobile site. (http://ift.tt/1YLswq7) Nested inside each checkbox there is the checkbox text/label, as well as a span element that has the word "Enable". I gave the span an onclick, which right now just does alert("HI") but here is what I would like it to do:

I would like the checkboxes to start off disabled, and then by clicking the span INSIDE the checkbox, the checkbox will enable. To enable the checkbox programmatically is simple, but the problem is this:

When the jquery checkbox is set to disabled, it disables everything inside of it - including the span that has the onclick to enable it!

<fieldset data-role="controlgroup">
                <label><input type="checkbox" id="checkbox1" disabled> <span onclick="enable()">Enable</span> Text of checkbox here. </label>
                
                <label><input type="checkbox" id="checkbox1" disabled> <span onclick="enable()">Enable</span> Text of checkbox here. </label>
                
                <label><input type="checkbox" id="checkbox1" disabled> <span onclick="enable()">Enable</span> Text of checkbox here. </label>
                
            </fieldset>

Is there any way to enable just that part of the textbox? Or maybe certain properties of the disabled checkbox can be changed inline by the span element? I've tried playing around, to no avail, because I don't understand what happens behind the scenes when the checkbox disables.




Creating dynamic checkboxes in play2 framework?

I have two lists, ListA is a list containing the name and value of would-be-generated set of checkboxes. ListB tells which ListA checkbox should be .

Here is the code:

@for((listA, index) <- model.ListA.zipWithIndex){
    @if(index % 4 == 0){
    <tr>
    }
    <td>
    @for(listB <- model.ListB){
    <input id="listB@index" name="listB[@index]" type="checkbox"
        value="@listA.codeVal" @(if(listA.codeVal == listB) "checked")/>
    <label>@listA.nameVal</label>
    }
    </td>
    @if(index % 4 == 3){
    </tr>
    }
}

The code above generates the checkboxes redundantly, not just a single set of ListA checkboxes with checks on them.

Ideal:

[/]CheckBox1 []CheckBox2 [/]CheckBox3 []CheckBox4

Actual:

[/]CheckBox1 [ ]CheckBox1 [ ]CheckBox1 [ ]CheckBox1

[ ]CheckBox2 [ ]CheckBox2 [ ]CheckBox2 [ ]CheckBox2

[ ]CheckBox3 [ ]CheckBox3 [/]CheckBox3 [ ]CheckBox3

[ ]CheckBox4 [ ]CheckBox4 [ ]CheckBox4 [ ]CheckBox4

Can you give me a clue on what I was doing wrong? Any help would be much appreciated. Thank you




lundi 28 décembre 2015

VBA: Trigger an Event in Form Control

I am working on a WBS in Excel with checkboxes.

I have the following:

[checkbox1] Level A
---------[checkBox2] item 1
---------[checkBox3] item 2
[checkbox4] Level B
---------[checkBox5] item 3

When I untick checkbox2 it will put an X in the cell next to item 1 If I tick checkbox2, it will remove the X.

If I untick checkbox1, it will untick checkbox2 and checkbox3, but it does not put an X in the cell next to the item 1 and 2. It just unticks the two checkboxes without triggering the event. How do I link that event to checkBox1?

If it is not possible to trigger that kind of event in Form Control, my other questions would be to know how to know the row and column where the checkbox is in ActiveX Control?

In Form Control we can use sheets("sheet1").checkboxes(application.caller), but this does not work in ActiveX Control.

The code for checkbox2 or checkbox3:

Sub CheckBoxLine()
Dim ws As Worksheet
Dim chk As CheckBox
Dim lColD, myCol As Long
Dim lColChk As Long
Dim lRow As Long
Dim rngD As Range
lColD = 1 'number of columns to the right
Set ws = ActiveSheet
Set chk = ws.CheckBoxes(Application.Caller)
lRow = chk.TopLeftCell.Row
lColChk = chk.TopLeftCell.Column
Set rngD = ws.Cells(lRow, lColChk + lColD)

Select Case chk.Value
Case 1   'box is checked
  rngD.Value = "X"
Case Else   'box is not checked
  rngD.Value = "X"

End Select

End Sub

The code for checkbox1:

Select Case chk.Value
Case 1   'box is checked
  For Each cb In ws.CheckBoxes
    If cb.Name = "Check box 2" Then
        cb.Value = 1
    End If

    If cb.Name = "Check box 3" Then
        cb.Value = 1
    End If
  Next cb

Case Else   'box is not checked
  For Each cb In ws.CheckBoxes
    If cb.Name = "Check box 2" Then
        cb.Value = 0
    End If

    If cb.Name = "Check box 3" Then
        cb.Value = 0
    End If
  Next cb
End Select




checkbox not visible when value is not null

i want to set visibility Check-box when server return value is not null but check-box is not visible

this is my code

    JSONObject json_Response = new JSONObject(response);
      String _RchAmount = json_Response.getString("pay_from_wallet");
      String _Remainbalance = json_Response.getString("ewalletbalance");
      String _InrPay =json_Response.getString("amt_collected");
          if(_Remainbalance==null)
             {
              _CheckBox.setVisibility(View.VISIBLE);
              confirm_payWallet.setText("Pay from  eWallet Rs. " + _RchAmount);
              confirm_payWallet.setVisibility(View.VISIBLE);
              confirm_TotalWallet.setText("Your current eWallet balance is Rs." + _Remainbalance);
              confirm_TotalWallet.setVisibility(View.VISIBLE);
            }

Myxml

 <CheckBox
    android:layout_width="40dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:id="@+id/check_wallet"
    android:textColorHint="@color/MediumVioletRed"
    android:layout_alignTop="@+id/pay_textView"
    android:visibility="invisible"
    />
<TextView
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_below="@+id/main_layout"
    android:layout_marginTop="11dp"
    android:layout_toRightOf="@+id/check_wallet"
    android:layout_marginRight="50dp"
    android:textColor="@color/Black"
    android:textStyle="bold"
    android:text=""
    android:gravity="center_vertical"
    android:id="@+id/pay_textView"
    android:visibility="invisible"
    />
<TextView
    android:layout_width="match_parent"
    android:layout_height="25dp"
    android:layout_below="@+id/pay_textView"
    android:layout_marginLeft="50dp"
    android:textStyle="bold"
    android:layout_marginRight="7dp"
    android:text=""
    android:id="@+id/status_wallet"
    android:visibility="invisible"
    />

i dont know where i am doing mistake Please help me




ACF Checkbox value

I have an Advanced Custom Field (repeater) setup. In the admin area of the page where these custom fields live are 3 options (Standard, Professional and Enterprise). It's setup so you can see what features are built in to each level of subscription. So there's 15 features. The Standard feature has the first 10 included. The Professional feature has the first 10 (as in the Standard) plus the next 3 features. The Enterprise level has the first 10 (as in the Standard) plus the 3 that the Professional level has and the last 2 features (only the Enterprise has the last 2 features).

I've been searching and trying many different things but cannot get what I'm after. I'm programming the page in 3 blocks on mobile to match the 3 levels. The first block will represent the Standard level and will list all 10 features it has. The next block will house the Professional level but instead of listing all the duplicate 10 that Standard has, it will read, "Same features as Standard, plus", then it will list the next 3 associated with the Professional level. Then comes the Enterprise level block. This will also read, " Same features and Standard and Professional, plus"... then it will list the last two features.

I'm having a real hard time getting the display to only display the features for Professional and Enterprise.

The code below is what I have now but because Enterprise has all of those features, it displays them all instead of just the features that only have Enterprise. The same with Professional. They are both displaying all the features that Standard has too because they all have them. I just cannot figure out the right check to only display the new features that the other doesn't have.

Here is my bit of code for Professional:

<?php $professional = get_sub_field('feature_software_version'); ?>
        <?php if( in_array('professional', $professional) ) { ?>
                <span class="featureshead"><?php the_sub_field('feature_headline'); ?></span><br />
            <?php } else { ?>
            <?php } ?>

Here is my bit of code for Enterprise:

<?php $enterprise = get_sub_field('feature_software_version'); ?>
        <?php if ( in_array('enterprise', $enterprise ) )  {    ?>

                <span class="featureshead"><?php the_sub_field('feature_headline'); ?></span><br />

        <?php } else { ?>
        <?php } ?>




check/uncheck checkboxes upon checking a checkbox

hi all i am trying to check a check box which upon checking will check remaining checkboxes present in the form using classes how can i do it??

enter code here
<!DOCTYPE html>
<html>
<head>

<script>
$(".global").on("click", function() {
var all = $(this);
$('.checkbtn').each(function() { 
$(this).prop("checked", all.prop("checked"));
});
});
</script>
</head>
<body>
<div>
     <input type="checkbox" class ="global" id="select-all" name="selectAll" value=""/> All
<input type="checkbox" class ="checkbtn" name="practice" value=""/> 1
<input type="checkbox" class ="checkbtn" name="filename" value=""/> 2
<input type="checkbox" class ="checkbtn" name="comment" value=""/> 3

 </div>
 </body>
 </html>




How to use checkbox groups in Laravel5.1

Here is Error

Creating default object from empty value

Here is a part of view

<div class="form-group">
    <label class="col-md-4 control-label">職種</label>
    <div class="col-md-6">
       <div class="col-md-6">
           <label class="checkbox-inline">
               <input type="checkbox" name="job[]" value="アカウント/企画営業" {{ $data->checkedJob('アカウント/企画営業') }}>
               アカウント/企画営業
           </label>
       <label class="checkbox-inline">
               <input type="checkbox" name="job[]" value="プロジェクトマネージャー/プロデューサー" {{ $data->checkedJob('プロジェクトマネージャー/プロデューサー') }}>
               プロジェクトマネージャー/プロデューサー
           </label>
       <label class="checkbox-inline">
               <input type="checkbox" name="job[]" value="Webディレクター" {{ $data->checkedJob('Webディレクター') }}>
               Webディレクター
           </label>
       <label class="checkbox-inline">
               <input type="checkbox" name="job[]" value="Webマーケター" {{ $data->checkedJob('Webマーケター') }}>
               Webマーケター
           </label>
       </div>
    </div>
</div>
<div class="form-group">
    <label class="col-md-4 control-label">スキル</label>
    <div class="col-md-6">
      <!-- タブ・メニュー -->
      <ul class="nav nav-tabs">
        <li class="active"><a href="#sampleContentA" data-toggle="tab">エンジニア・デザイナー</a></li>
        <li><a href="#sampleContentB" data-toggle="tab">ビジネス</a></li>
      </ul>
      <!-- タブ内容 -->
      <div class="tab-content">
        <div class="tab-pane active" id="sampleContentA">
          <p>Web制作</p>
           <input type="checkbox" name="tech_skill[]" value="XHTML" {{ $data->checkedTech('XHTML') }}>XHTML
           <input type="checkbox" name="tech_skill[]" value="HTML" {{ $data->checkedTech('HTML') }}>HTML
           <input type="checkbox" name="tech_skill[]" value="CSS" {{ $data->checkedTech('CSS') }}>CSS
        </div>

        <div class="tab-pane" id="sampleContentB">
          <p>Webマーケティング</p>
           <input type="checkbox" name="biz_skill[]" value="Webディレクション" {{ $data->checkedBiz('Webディレクション') }}>Webディレクション
           <input type="checkbox" name="biz_skill[]" value="GoogleAdSense" {{ $data->checkedBiz('Google AdSense') }}>Google AdSense

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

Here is a part of ProfileController

public function postUpdate(Request $request)
{
    // バリデーション
    $inputs = $request->all();

    // ルール
    $rules = [
        'tw_id'=>'max:100',
        'fb_id'=>'max:100',
        'url'=>'url|max:200',
        'comment'=>'max:500'
    ];

    $message = [
        'tw_id'=>'TwitterIDは100文字以内で記入してください。',
        'fb_id'=>'FacebookIDは100文字以内で記入してください。',
        'url.url' => 'URLは正しい形式で指定してください。',
        'url.max' => 'URLは200文字以内で指定してください。',
        'comment.max' => 'コメントは500文字以内で記入してください。',
    ];

    $validator = \Validator::make($inputs,$rules,$message);

    if($validator->fails()){
      return redirect()->back()->withErrors($validator->errors())->withInput();
    }

    // ユーザー情報取得
    $user = Auth::user();
    $name = $user->name;

    // Profileテーブルのデータ取得
    $data = Profile::where('name','=',$name)->first();

    $job = $request->job;
    $jobImp = implode(',',$job);
    $data->job = $jobImp;

    $tech = $request->tech_skill;
    $techImp = implode(',',$tech);
    $date->tech_skill = $techImp;

    $biz = $request->biz_skill;
    $bizImp = implode(',',$biz);
    $date->biz_skill = $bizImp;

    $data->tw_id = $request->tw_id;
    $data->fb_id = $request->fb_id;
    $data->url = $request->url;
    $data->comment = $request->comment;

    $data->save();

    \Session::flash('flash_message', 'プロフィール情報を更新しました!');

    return redirect()->to('mypage');
}

Here is a part of Profile

Schema::create('profile', function (Blueprint $table) {
      $table->increments('id');
      $table->rememberToken();
      $table->timestamps();
      $table->string('name')->foreign('users')->on('name');
      $table->text('profile_image_name',200);
      $table->text('job',50)->nullable();
      $table->text('tech_skill',500)->nullable();
      $table->text('biz_skill',500)->nullable();
      $table->string('tw_id',100)->nullable();
      $table->string('fb_id',100)->nullable();
      $table->string('url',200)->nullable();
      $table->string('comment',500)->nullable();
  });

When i use only checkbox group(job[]),i have no errors with in my code.

What is wrong with this code? How do i use checkbox groups in Laravel5.1?




Bootstrap is not working after partial postback with asp.net update panel

I have some checkbox with bootstrap style sheet "Flat", initially they are showing as expected, they are in between the update panel. When the page partially updated through updatepanel the stylesheet of the Checkbox lost and seems to be not working. please suggest




Dependent checkbox on array input checkboxes

I have two array checkboxes namely chk1 & chk2 this checkboxes data are generated dynamically. When i check chk1 UK means chk2 90 has to be checked. if US means 60 has to be checked and so on. any suggestion to do this task?

<input type="checkbox" name="chk1" id="chk1" value="UK"> UK
<input type="checkbox" name="chk1" id="chk1" value="US"> US
<input type="checkbox" name="chk1" id="chk1" value="IN"> IN

<input type="checkbox" name="chk2" id="chk2" value="90"> 90
<input type="checkbox" name="chk2" id="chk2" value="60"> 60
<input type="checkbox" name="chk2" id="chk2" value="10"> 10




Php form checked when the checkbox value in array mysql query?

I have and value in my database. It's call type

I have 2 checkbox in my html form.

<input name="barea[]" type="checkbox" id="barea[]" value="1" {$cbvar}/>Normal 
<input name="barea[]" type="checkbox" value="2" id="barea[]" {$cbvar}/>Gold

And I store data as code below:

$checkboxvar = implode(',', $_GET['barea']);

So my table data like:

+-------+-----------+
| ID    | type      |
+-------+-----------+
| 1     | 1         |
| 2     | 1,2       |
| 3     | 2         |
| 4     | 1,2       |
| 5     | 1,2       |
| 6     | 1         |
+-------------------+

When user edit this data, how to checked the checkbox when the barea[] value exist in_array in the mysql_query?

I try the below coding, in my php file:

$checkbox = explode(',',$row['type']);
if (in_array($_GET['barea'],$checkbox)){
    $cbvar = "checked=\"checked\"";
}else{
    $cbvar = '';
}

In my html

<input name="barea[]" type="checkbox" id="barea[]" value="1" {$cbvar}/>Normal 
<input name="barea[]" type="checkbox" value="2" id="barea[]" {$cbvar}/>Gold

But it can't work, i think maybe the problem is on if (in_array($_GET['barea'],$checkbox)){.

so how to improve my coding, or any other good coding suggestion? thank you.




dimanche 27 décembre 2015

Allow user to select only 1 item in Recycle View Android

Hi I have a RecycleView and an adapter with CheckBox that allow user to select multiple item in the Recycle view (checked item will be store in an ArrayList) Now I want to add another function that allow user to only choose 1 item in the Recycle view (only 1 checkbox is checked) (User can change the selection freely). How to implement this. Any help is much appreciate

Here is my apdater (for select multiple item) (I want to modify or add another adpater to allow user to select only 1 item, only 1 checkbox is checked at a time)

public class EventAdapterAssign extends RecyclerView.Adapter {

private Context context;
List <Event> events, eventSelected;

public EventAdapterAssign(Context context, List<Event> events, List<Event> eventSelected) {
    this.context = context;
    this.events = events;
    this.eventSelected = eventSelected;
}


@Override
public EventAdapterAssign.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    // Inflate the custom layout
    View eventView1 = inflater.inflate(R.layout.event_list_assign, parent, false);

    // Return a new holder instance
    ViewHolder viewHolder = new ViewHolder(eventView1);
    return viewHolder;
}

@Override
public void onBindViewHolder(EventAdapterAssign.ViewHolder holder, int position) {
    //Getting the particular item from the list
    final Event event = events.get(position);

    //Showing data on the views
    holder.EventTitle.setHint(event.getEventTitle());
    holder.EventDesc.setText(event.getEventDesc());
    holder.EventStartTime.setText(event.getEventStartTime());
    holder.EventEndTime.setText(event.getEventEndTime());
    holder.EventID.setText(event.getEventID());

    //in some case, it will prevent unwanted situations;
    holder.selectCheckBox.setOnCheckedChangeListener(null);

    //if true, your check box will be selected, else unselected
    holder.selectCheckBox.setChecked(event.isSelected());

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

            event.setIsSelected(isChecked);
            if (isChecked) {
                eventSelected.add(event);
            } else {
                eventSelected.remove(event);
            }
        }
    });

}

// Return the total count of items
@Override
public int getItemCount() {
    return events.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    //View
    public EditText EventTitle;
    public TextView EventDesc;
    public TextView EventStartTime;
    public TextView EventEndTime;
    public TextView EventID;
    public CheckBox selectCheckBox;

    //initiating View
    public ViewHolder(View itemView) {
        super(itemView);

        // display Check In event when beacon in range

        EventTitle = (EditText)itemView.findViewById(R.id.EventTitle);
        EventDesc = (TextView)itemView.findViewById(R.id.EventDesc);
        EventStartTime = (TextView)itemView.findViewById(R.id.EventStartTime);
        EventEndTime = (TextView)itemView.findViewById(R.id.EventEndTime);
        EventID = (TextView)itemView.findViewById(R.id.EventID);

        selectCheckBox = (CheckBox)itemView.findViewById(R.id.selectCheckBox);

    }
}

and here is my data model (Event) class

public class Event implements Parcelable {
    private String EventID;
    private String EventDesc;
    private String EventTitle;
    private String EventStartTime;
    private String EventEndTime;

    private Context context;
    private boolean isSelected;

    public boolean isSelected() {
        return isSelected;
    }

    public void setIsSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }

    public String getEventID() {
        return EventID;
    }

    public void setEventID(String eventID) {
        EventID = eventID;
    }

    public String getEventDesc() {
        return EventDesc;
    }

    public void setEventDesc(String eventDesc) {
        EventDesc = eventDesc;
    }

    public String getEventTitle() {
        return EventTitle;
    }

    public void setEventTitle(String eventTitle) {
        EventTitle = eventTitle;
    }

    public String getEventStartTime() {
        return EventStartTime;
    }

    public void setEventStartTime(String eventStartTime) {
        EventStartTime = eventStartTime;
    }

    public String getEventEndTime() {
        return EventEndTime;
    }

    public void setEventEndTime(String eventEndTime) {
        EventEndTime = eventEndTime;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.EventID);
        dest.writeString(this.EventDesc);
        dest.writeString(this.EventTitle);
        dest.writeString(this.EventStartTime);
        dest.writeString(this.EventEndTime);
    }

    public Event() {
    }

    protected Event(Parcel in) {
        this.EventID = in.readString();
        this.EventDesc = in.readString();
        this.EventTitle = in.readString();
        this.EventStartTime = in.readString();
        this.EventEndTime = in.readString();
    }

    public static final Parcelable.Creator<Event> CREATOR = new Parcelable.Creator<Event>() {
        public Event createFromParcel(Parcel source) {
            return new Event(source);
        }

        public Event[] newArray(int size) {
            return new Event[size];
        }
    };


}




EmberJS checkbox set value

According to the ember documentation, I can do this:

{{input type="checkbox" name="fruits[]" checked=isAdmin}}

This works fine, however... my checkbox, although 'on or off' but consider the following:

[ ] Apples
[ ] Blueberries
[ ] Oranges

Let's say the 'value' for each one of those is the label... so if someone where to check all 3, it would pass this as an array:

["Apples","Blueberries","Oranges"]

However, this isn't what happens...I get:

["true","true","true"]




Add a checkbox inside a JQuery draggable element

I am working on an webpage that assigns summer campers to activities. The display page shows each activity as a JQuery draggable target, and campers are displayed as draggable items. The camp staff can run the algorithm, and then correct it by dragging a camper from one activity to another. So far, so good.

The wrinkle here is that I'd like a way for camp staff to mark certain camper assignments as "permanent", so that when the algorithm runs again, those campers are not moved from their choices. So for example, if camper A is assigned to Swimming, and that is ideal for her, I want a way for the camp staff to signal that. I was thinking the ideal thing would be a checkbox inside the camper display boxes: if the staff checks the box, then the algorithm will not change that assignment.

Is there a way to put a checkbox inside a Draggable element? I saw this posting about checkboxes:

Checking a checkbox with jQuery?

But it did not say if it was possible to put a checkbox inside a Draggable. Can this be done?

Thanks in advance for any help here.




CheckBox isCheked returns true but visually is not checked

I'm trying to initialize a checkbox listview from an array. To do so I'm looping through listview items and checking if the item exists or doesn't, if it does then I set it to checked. Thing is it doesn't really work as expected. Internally everything works just fine, the result array is correct, but visually it doesn't display the checkboxes in their correct state.

This is the function which initializes the checkboxes, it is called by onCreate and onResume methods.

public void init()
{
    View v;
    CheckBox checkbox;
    for (int i = 0; i < LIST.getCount(); i++) {
        v = LIST.getAdapter().getView(i, null, null);
        checkbox = (CheckBox)v.findViewById(R.id.checkbox);
        MyClass c = (MyClass) adapter.getItem(i);
        if(List_to_compare.contains(c)) {
            Log.i("Before", String.valueOf(checkbox.isChecked())); //returns false
            checkbox.setChecked(true);
            Log.i("After", String.valueOf(checkbox.isChecked())); //returns true
        }
    }
}

But the checkbox is not visually checked. If more code is needed, let me know, really struggling with this one.




Checkbox always checked PHP/HTML

I'm trying to check what checkboxes are checked, and perform a file deletion depending on what checkboxes are checked. To me it seems like they ALWAYS have a value even if their not checked if I got the value".." in the checkbox. I currently removed the value in the checkbox, dident seem to make any diffrence.

Every checkbox is given a unique number, at the same time file its supposed to delete have the same index with its file name as data. But it NEVER sees that any of the checkboxes are even checked.. No errors, just not doing anything.. Please help

how it looks now picture

HTML and php:(document im working on is called protected.php)

<form action="protected.php" method="post"><br>

<input type="submit" name="Delete" value="Delete">

</form>


<?php

echo 'My files';
"<br>";
$mydr = "D:\wamp\www\\";
$dir = $mydr . $_SESSION['userid'];

// Open a directory, and read its contents
$checkbox_gen = 0;
$filename_gen = array();

if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while ((($file = readdir($dh)) !== false)){

        if($file != '.' && $file != '..'){
        echo "<form><input type=\"checkbox\" name=\"$checkbox_gen\" id=\"checkbox\">" . "<a href=\"$dir/$file\">$file</a></form>" . "<br>";
        $filename_gen[$checkbox_gen] = $file;
        $checkbox_gen += 1;
        }
        }

    closedir($dh);
  }
}

?>

<br>
<form action="protected.php" method="post"><br>

<input type="submit" name="Delete" value="Delete">

</form>

<?php

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

    for($i = 0; $i < 10; $i++){
        if(!empty($_POST[$i])) {
            echo $i . 'is checked';
            //$temp = $dir . '\\' . $filename_gen[$i];
            //unlink($temp);
            echo $temp;
        }

    }
}


?>




Binding two checkboxes together

I have two checkboxes

<input class="checkbox1" type="checkbox" name='1' id="example1" value="example1"/> 

and

<input class="checkbox2" type="checkbox" name='2' id="example2" value="example2"/>

Is it possible to connect these two checkboxes, so that whatever happens to the 'checked' attribute of one checkbox also happens to the other? It needs to work for

  1. User changes the checked status

  2. Some javascript function changes the checked status

My actual example is very complex and has many many checkboxes. So I am looking for a solution where I can just determine a connection between two checkboxes and never have to think about it again. thanks carl




samedi 26 décembre 2015

Cancel triggering of click event on checkbox selection

I have this piece of HTML:

<tr class="acord">
 <td colspan="4"><input class="marcatodos" type="checkbox" value="1"/>Clientes</td>
</tr>
<tr>
   <td>
      <label>
      <input name="vCliente" class="marcar" type="checkbox" checked="checked" value="1" />
      <span class="lbl"> Visualizar Cliente</span>
      </label>
   </td>
   <td>
      <label>
      <input name="aCliente" class="marcar" type="checkbox" value="1" />
      <span class="lbl"> Adicionar Cliente</span>
      </label>
   </td>
   <td>
      <label>
      <input name="eCliente" class="marcar" type="checkbox" value="1" />
      <span class="lbl"> Editar Cliente</span>
      </label>
   </td>
   <td>
      <label>
      <input name="dCliente" class="marcar" type="checkbox" value="1" />
      <span class="lbl"> Excluir Cliente</span>
      </label>
   </td>
</tr>

and this jQuery script:

$(".acord").click(function() {
   $(this).next("tr").slideToggle(1);
});

That's what the HTML generates:

enter image description here

The jQuery hides the row below the one with a title (class accord)

My problem is that when I click on the checkbox, the jQuery triggers it anyway.

How can I make it so the function only runs when I click outside the checkbox?




Disable changing of checkbox in listView android

Is it possible to disable the user clicking a checkbox item in a listView in android? I have a listView where the programme decides what is checked and not checked and I dont want the user changing the state of the checkboxes. Is there an easy way to do this?

I have tried setting the setClickable to false but that didnt work.

Thanks




Codeigniter checkbox returns always 0

I've a form to add a project with a checkbox if the project is already finished or not. This is the html in the view (codeigniter):

<div class="form-group">
                            <label>Task completed:</label>
                            <input type="checkbox" class="form-control" id="task_completed" name="task_completed" />
                            <?php echo form_error('task_completed'); ?>

                        </div>

I load the data in my controller:

$checked = (int)$this->input->post('task_completed');

when i do a echo "" . $checked; it's always 0!! Also, in my database. Where is my fault?




Filtering DOM elements according to inputs - JavaScript

I have a problem such this:

There are several checkboxes and I want to filter some document elements according the states (checked/unchecked) of these checkboxes.

On first load of the page all items are shown. The if checkbox(es) is(are) checked - only items having at least one these attributes will be showed. If checked item is unchecked again - the hidden elements (hidden - because of verily this check action) will appear again.

My plan to achieve this:

  1. Declare empty arrays:
  2. Push them values from checkboxes (with onchange). If a value is already there, remove that element.
  3. Check interested DOM elements have at least one element from these arrays

I tried something and here is my code. But don't know what am I doing wrong - I even can not estimate what is happening when checking the boxes.

Any help about fixing this unusual behaviour, coding style, and refactoring of the code is appreciated. Also feel free to refer to a library/plugin dealing with that kind of filtering :)

P.S. BTW, guides with map, filter, some, every are more appreciated ;-)

<!DOCTYPE html>
<html>
<head>
        <title></title>
</head>
<body>
<script type="text/javascript">
        var countries = [];
        var collections = [];
        var brands = [];

        function cnt(x) {
                if (countries.indexOf(x) == -1)
                { 
                        countries.push(x);
                        console.log(x+" pushed to countries");
                }
                else 
                {
                        i = countries.indexOf(x);
                        countries.splice(i,1);
                        console.log(x+" removed from countries");
                }
                console.log(countries);
        }

        function brnd(x) {              
                if (brands.indexOf(x) == -1)
                {               
                        brands.push(x);
                        console.log(x+" pushed to brands");
                }
                
                else 
                {
                        i = brands.indexOf(x);
                        brands.splice(i,1);
                        console.log(x+" removed from brands");
                }

                console.log(brands);
        }
        
        function col(x) {
                
                if (collections.indexOf(x) == -1)
                {
                        collections.push(x);
                        console.log(x+" pushed to collections");
                }
                else 
                {
                        i = collections.indexOf(x);
                        collections.splice(i,1);
                        console.log(x+" removed from collections");
                }
                console.log(collections);
        }

        function unuseful(el) {

                if ((countries.length > 0) || (countries.length > 0) || (countries.length > 0))
                {       
                        country_index = countries.indexOf(el.dataset.country);
                        brand_index = brands.indexOf(el.dataset.brand);
                        collection_index = collections.indexOf(el.dataset.collection);
                        s = country_index + brand_index + collection_index;

                return s == -3;
                }
                return false;
        }

        function h(x) {
                x.style.display = 'none';
        }

        function hideBitches() {

                var context = document.getElementById("products");
                var items = context.getElementsByClassName("item");

                for(j=0; len=items.length, j<len; ++j) {
                        if(unuseful(items[j])) {
                                h(items[j]);
                                console.log(items[j]+" is hidden")
                        }                               
                }
        }

</script>

<div id="countries">
                        <input type="checkbox" name="country" value="1" onchange="cnt(this.value); hideBitches()">
                Poland                  
                        <input type="checkbox" name="country" value="2" onchange="cnt(this.value); hideBitches()">
                Germany                 
                        <input type="checkbox" name="country" value="3" onchange="cnt(this.value); hideBitches()">
                Venezuela                       
                        <input type="checkbox" name="country" value="4" onchange="cnt(this.value); hideBitches()">
                Cuba                    
                
</div> 
<div id="brand">
                        <input type="checkbox" name="brand" value="1" onchange="brnd(this.value); hideBitches()">
                Laviva                  
                        <input type="checkbox" name="brand" value="2" onchange="brnd(this.value); hideBitches()">
                Parmesan                        
                        <input type="checkbox" name="brand" value="3" onchange="brnd(this.value); hideBitches()">
                Mercenarios                     
                        <input type="checkbox" name="brand" value="4" onchange="brnd(this.value); hideBitches()">
                Penguin                 
                        
</div>
<div id="collection">
                        <input type="checkbox" name="col" value="1" onchange="col(this.value); hideBitches()">
                Mephistopheles                  
                        <input type="checkbox" name="col" value="2" onchange="col(this.value); hideBitches()">
                Marsupial                       
                        <input type="checkbox" name="col" value="3" onchange="col(this.value); hideBitches()">
                Cangaroo                        
                        <input type="checkbox" name="col" value="4" onchange="col(this.value); hideBitches()">
                Aufhebung                       
                        <input type="checkbox" name="col" value="5" onchange="col(this.value); hideBitches()">
                Nestor Makhno                   
                        
</div>
<input type="submit" name="submit" value="search">

<div id="products">
                                <div class="item" data-country="3" data-collection="3" data-brand="3">
                                <p>Eternal cn 3br 3 cl 3</p>
                                <img src="/store/media/file000466623310.jpg" style="width:100px; height:50px">
                                <p>300*15*15</p>                            
                        </div>            
                                <div class="item" data-country="2" data-collection="3" data-brand="1">
                                <p>Eternity cn 2br 1 cl 3</p>
                                <img src="/store/media/file000466623310.jpg" style="width:100px; height:50px">
                                <p>320*15*12</p>                            
                        </div>            
                                <div class="item" data-country="4" data-collection="2" data-brand="2">
                                <p>Ether cn 4br 2 cl 2</p>
                                <img src="/store/media/file000466623310.jpg" style="width:100px; height:50px">
                                <p>330*20*15</p>                            
                        </div>            
                                <div class="item" data-country="2" data-collection="3" data-brand="1">
                                <p>Leather cn 2br 1 cl 3</p>
                                <img src="/store/media/file000466623310.jpg" style="width:100px; height:50px">
                                <p>350*25*18</p>                            
                        </div>            
                                <div class="item" data-country="3" data-collection="1" data-brand="4">
                                <p>FLeather cn 3br 4 cl 1</p>
                                <img src="/store/media/file000466623310.jpg" style="width:100px; height:50px">
                                <p>350*25*18</p>                            
                        </div>            
                                <div class="item" data-country="2" data-collection="4" data-brand="3">
                                <p>Feather cn 2br 3 cl 4</p>
                                <img src="/store/media/file000466623310.jpg" style="width:100px; height:50px">
                                <p>250*15*28</p>                            
                        </div>            
                                <div class="item" data-country="4" data-collection="3" data-brand="2">
                                <p>Weather cn 4br 2 cl 3</p>
                                <img src="/store/media/file000466623310.jpg" style="width:100px; height:50px">
                                <p>250*16*28</p>                            
                        </div>            
                                <div class="item" data-country="3" data-collection="1" data-brand="2">
                                <p>Theatre cn 3br 2 cl 1</p>
                                <img src="/store/media/file000466623310.jpg" style="width:100px; height:50px">
                                <p>150*20*18</p>                            
                        </div>            
                                
</div>
</body>
</html>



How to get the value of a checkbox jsp

I have this code in my HTML

<input type="checkbox" name="news" value="news">

How can i check if it is selected in the jsp file that the form send its data. I tried the code below but it shows me an error. When i say error i mean that it is going into my error page which does not say anything. JSP

String news = request.getParameter("news");

Is there any way to check it from my jsp?




How to select all checkboxes in Meteor form, then save value to Database

I've got a form that allows users to select some options which are then saved to the database. There are a lot of options and in most cases users will want to select them all.

Currently, I have it set up so that when each checkbox is clicked either on or off, it automatically updates the database boolean BUT I don't think this is the best way to do this. It also means if I put in some jQuery to select all checkboxes then the database values don't update.

So what I'm looking for is a way to make a checkbox or button that selects all checkboxes in a form, then a submit button that gets the value of all the checkboxes and saves them in to the database. The information is not sensitive so it can be saved to the user profile

My checkboxes are just normal checkboxes with unique id's in a form

Here is my JS (I've commented each block so you see what it does

if (Meteor.isClient) {

  //this block sets each alert value in the db to false as default
  Template.chooseAlerts.onCreated(function () {
    Meteor.users.update({ _id: Meteor.userId() }, {$set: { 'profile.chargeSucceeded': false, 'profile.chargeFailed': false, 'profile.chargeRefunded': false, 'profile.customerCreated': false, 'profile.customerDeleted': false, 'profile.subscriptionCreated': false,'profile.subscriptionUpdated': false,'profile.subscriptionDeleted': false, 'profile.trialEnding': false}});
  });

  //this is the logic for submitting the form, it flashes a message to the user and moves to the next page (this is where I'll need to store the checkbox values to the db
  Template.chooseAlerts.events({
    'submit #chooseAlerts': function(e) {
      e.preventDefault();
      var submitButton = $('button[type="submit"]').button('loading');
      sAlert.success('Great, we\'ve saved those alerts!', {onRouteClose: false, timeout: 2500});
      Router.go('subscribe');
      submitButton.button('reset');   
    },

    //the following blocks are just events for changing the db value when a checkbox is clicked. There are more of these but they are all the same so I have excluded them
    'click #chargeSucceeded': function(evt) {
      var value = evt.target.checked;
      Meteor.users.update({ _id: Meteor.userId() }, {$set: { 'profile.chargeSucceeded': value}});
    },
    'click #chargeFailed': function(evt) {
      var value = evt.target.checked;
      Meteor.users.update({ _id: Meteor.userId() }, {$set: { 'profile.chargeFailed': value}});
    },
    'click #chargeRefunded': function(evt) {
      var value = evt.target.checked;
      Meteor.users.update({ _id: Meteor.userId() }, {$set: { 'profile.chargeRefunded': value}});
    },
    'click #customerCreated': function(evt) {
      var value = evt.target.checked;
      Meteor.users.update({ _id: Meteor.userId() }, {$set: { 'profile.customerCreated': value}});
    },
    'click #customerDeleted': function(evt) {
      var value = evt.target.checked;
      Meteor.users.update({ _id: Meteor.userId() }, {$set: { 'profile.customerDeleted': value}});
    }
  });




How to ensure different option with different checkbox

Hello I need to find solution for my site. I have more checkboxe option and dependiong on the checkboxe I decide to check I would like to get different option offer from the script. Means that for example if I check the value 1 I would like to get the offer Ping and Basic info and so on. Can you please somebody help me with that how to write in in javascript or jquery. Thank you so much!

    <div class="checkbox">
    <label>
    <input type="checkbox" value="1" onclick="call_the_script()">
    </label>
    <label>
    <input type="checkbox" value="2" onclick="">
    </label>
    <label>
    <input type="checkbox" value="3">
    </label>
    </div>

<div class="col-xs-10">
<input type="hidden" name="form_type" value="script">
<select id="option" class="form-control input-sm" name="option">

<option value="Ping">Ping</option>
<option value="Basic info">Basic info</option>
<option value="Restart modules">Restart modules</option>
</select>
</div>




Checkbox Listview for SpaRss

I Try customize "spaRSS" http://ift.tt/1eo1bVT, the default code of RSS option is

public void onClickOk(View view) {
    for (int topic = 0; topic < TOPIC_NAME.length; topic++) {
        if (((CheckBox) findViewById(CB_IDS[topic])).isChecked()) {
            String url = "http://ift.tt/1mFHU62" + Locale.getDefault().getLanguage() + "&output=rss";
            if (TOPIC_CODES[topic] != null) {
                url += "&topic=" + TOPIC_CODES[topic];
            }
            FeedDataContentProvider.addFeed(this, url, getString(TOPIC_NAME[topic]), true);
        }
    }

and The Result enter image description here

I want to add another Rss Feed, How?




vendredi 25 décembre 2015

I am geting checkbox items checked after collapsing the Grid and click again to visible the grid

I am getting ID from database in event handler.

private void buttonAddRooms_Click(object sender, RoutedEventArgs e) { EditRoomsDataGrid.Visibility = Visibility.Collapsed; AddRoomsDataGrid.Visibility = Visibility.Visible;

        Room room = new Room();
        RoomFactory fac = new RoomFactory();
        room.Room_ID = fac.RoomID();
        txtRoomID.Text = room.Room_ID.ToString();


        //COBbadspace.SelectedItem = -1;


     }

as button savedclick all the values from the form once inserted into the data base but again when i click addroombutton to visible the grid all the last checked items show checked so i want a way that when i click addroombutton to visible grid all the checkboxes unchecked and textboxes cleared/empty because as i click again to visible grid all the values still there. clbfacilities is a checklist box containing comboboxItems.

private void btnSaveRoom_Click(object sender, RoutedEventArgs e)
    {
        Room room = new Room();
        RoomFactory fac=new RoomFactory();
        room.RoomType = COBbadspace.SelectionBoxItem.ToString();
       // room.RoomType = txtbadsapace.Text;

        foreach (var item in clbFacilities.SelectedItems)
        {
            room.RoomFacilities += (item as ComboBoxItem).Content + ",";
        }
        String price = txtRoomPrice.Text;
        room.Room_Price = Convert.ToInt32(price);
        if (rbAvailable.IsChecked ?? false)
            room.Room_Status = true;
        else
            room.Room_Status = false;
        if (fac.Insert(room))

         {
            MessageBox.Show("insert");

         }
        else
            MessageBox.Show("not insert");

        AddRoomsDataGrid.Visibility = Visibility.Collapsed;
        EditRoomsDataGrid.Visibility = Visibility.Collapsed;
        viewRoomsGrid.Visibility = Visibility.Visible;


    }




jeudi 24 décembre 2015

Enabling two (or a fixed amount) checked in a checkbox/radio button scenario

Alright, here's the case.

Imagine that there's a rectangle with 4 points on it, naming rodUpLeft, rdoUpRight, rdoDownLeft, rdoDownRight as checkbox

I want to make sure that there's exactly TWO checked box checked AT ALL TIMES

Kind of like how radio button works, except instead of just one button got checked, I want two.

So I've tweaked around and came up with a code as below

    If sender.name = firstChoice Then
        sender.checked = True
    ElseIf Not lastChoice = sender.name Then
        Select Case lastChoice
            Case "rdoUpRight"
                rdoUpRight.Checked = False
            Case "rdoUpLeft"
                rdoUpLeft.Checked = False
            Case "rdoDownRight"
                rdoDownRight.Checked = False
            Case "rdoDownLeft"
                rdoDownLeft.Checked = False
        End Select
        lastChoice = firstChoice
        firstChoice = sender.name
    End If

So my initially idea is to track the buttons that were clicked, and uncheck the old button when a new unchecked button is clicked.

However, it does not stop the user from unchecking already checked checkbox, thus breaking the rest of the code.

A help would be much appreciated.




android, listview with checked box

I've read some posts about this matter but still I can't get it to working. I want to have a listview with a checkbox. Here's my activity_choose_songs.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/songs_to_choose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/sd_cards_playlist"
        android:textStyle="bold"
        android:gravity="center"
        android:textSize="30sp"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        />

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:listSelector="@drawable/list_selector"
        android:divider="#242424"
        android:dividerHeight="1dp"
        android:layout_below="@+id/songs_to_choose">
    </ListView>

</RelativeLayout>

And here's the layout for a specific item:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:padding="5dp"
    android:background="@drawable/list_selector">

    <CheckedTextView
        android:id="@+id/checkedTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:padding="10dp"
        android:gravity="center"
        android:drawableStart="?android:attr/listChoiceIndicatorMultiple"
        android:textColor="#f3f3f3" />

</LinearLayout>

Here's extract from onCreate() method in an activity where I want this listview to be displayed:

ListAdapter adapter = new SimpleAdapter(getApplicationContext(),chosenSongsListData,
                R.layout.playlist_checked_item,new String[]{"songTitle"},new int[]{R.id.checkedTextView});

        setListAdapter(adapter);
        ListView lw = getListView();

        lw.setItemsCanFocus(false);
        lw.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);

        lw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });

Yet, when I'm starting the activity and I' trying to check it, it looks like (the screen is in pressed state): enter image description here

What's wrong with my approach?




how to check the checked dynamic multiple choice checkbox if the form is not submitted in php mysql

Course prepare($sql); $st->execute(); while($coursers=$st->fetch(PDO::FETCH_ASSOC)) { $rs=$coursers['course']; $idrs=$coursers['id']; ?> " />


checked = true, from earlier checkbox

I have a question regarding the checkbox. I have 2 html pages. In the first one, there are checkboxes, which can be checked by the user. After pressing the submit button, the second page loads containing the same checkboxes, which now should be checked="true", if the user checked them in the first html page. How can I do this second html page? I assume I have to use expression language. My project is made with Spring Boot and Thymeleaf as expresison language.




Bootstrap Checkbox always return on

I am using bootstrap checkbox. the code for getting value and checkbox is bellow

    $( document ).ready(function() {
      
      var mycheckboxNewVal;
      
      var mycheckboxVal = $('#mycheckbox').val();
      
      if(mycheckboxVal == 'on')
        {
          mycheckboxNewVal==1;
        }
      else
        {
          mycheckboxNewVal==0;
        }
          
      alert("mycheckboxNewVal :"+mycheckboxNewVal);

       
      
    });
    <div class="col-sm-1-5"><label class="control-label" for="pwd">Check Box </label></div>
      <div class="col-sm-1">
        <span class="button-checkbox">
                <input type="checkbox" class="hidden" checked id="mycheckbox"/>
                <button type="button" class="btn-chk" data-color="success"></button>
        </span>
    </div>        

When I do 'alert("mycheckboxNewVal :"+mycheckboxNewVal);' I always get value 1.

Where am I making mistake?




JQgrid not checking the Header Checkbox when all checkboxes are checked in the table

Here I am facing a problem. When I do check all the row checboxes, the header checkbox doesnt seem to get checked automatically. Moreover it works vice-versa.

 datatype: "json",
    contentType: 'application/json',
    ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
    colNames: ['Id', 'Machine Name', 'IP Address', 'Discovered Date', 'Agent Install Status', 'Agent Installation Date', 'Agent Status', 'Agent Version', 'Last HeartBeat Received'],
    colModel: [            
        { name: 'id', hidden: false, width: 20, key: true, sorttype: 'int', search: true },
        { name: 'machineName', width: 120, search: true },
        { name: 'ipAddress', width: 60, search: true },
        //{ name: 'discoveredDate', width: 110, formatter: 'date', formatoptions: { srcformat: 'y-m-d', newformat: 'l, F d, Y' } },
        { name: 'discoveredDate', width: 110, search:true, formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } },
        { name: 'agentInstallStatus', width: 100, search: true },
        { name: 'agentInstallationDate', width: 110, search:true, formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } },
        { name: 'agentStatusName', width: 60, search: true },
        { name: 'agentVersion', width: 50, search: true },
        { name: 'lastHeartBeatRecieved', width: 110, search:true,formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } }
    ],
    rowattr: function (rd) {
        if (rd.agentInstallStatus != 'Completed' && rd.agentInstallStatus != 'Upgrade Completed' && rd.agentInstallStatus != 'Uninstallation Failed') {
            return {
                "class": "ui-state-disabled ui-jqgrid-disablePointerEvents"
            };
        }
    },

    sortname: 'id',
    sortorder: 'asc',
    loadonce: true,
    viewrecords: true,
    gridview: true,      
    width: gwdth,
    height: 650,
    sortable:true,
    rowNum: 30,        
    rowList: [10, 20, 30],
    mtype: 'GET',
    multiselect: true,
    multipleSearch: true,
    pager: "#jqGridPager",
    loadBeforeSend: function (xhr) {
        var authData = localStorageService.get('authorizationData');

        if (authData) {
            xhr.setRequestHeader("Authorization", 'Bearer ' + authData.token);
        }
        return xhr;
    }
});

jQuery("#jQGridMonitoredMachines").jqGrid('navGrid', '#jqGridPager',
{ edit: false, add: false, del: false, search: true }, {}, {}, {}, { closeAfterSearch: true });
});

Current Situation

It should be like in the below image.

enter image description here

How this can be achieved?