dimanche 30 avril 2017

Tracking average of two progress bar with checkboxes

I'm developing a very important project where the user can change the values of "pressure" of two elements via checkboxes. These checkboxes has two different values, one for bar-one and the second for bar-two. All this system has a "status panel" that says if it's all ok, or if there's a problem.

Please note that I don't have to use echoes or alert messages, because I need to show different div's depending on the current status of both bars.

I did the best I can in the snippet, I'm new to JavaScript so please don't be mean with my errors.

var 
    even = $('.even'),
    high = $('.high'),
    low = $('.low');

$('input').on('click', function() {
    var emptyValue = 0;
    $('input:checked').each(function() {
        emptyValue += parseInt($(this).val());
    });
    $('.bar-one').css('width', emptyValue + '%').attr('aria-valuenow', emptyValue);
});

if (average === 5) {
    even.show();
  } else {
    even.hide();
  }
  
if (average >= 7) {
    high.show();
  } else {
    high.hide();
  }
  
if (average <= 3) {
    low.show();
  } else {
    low.hide();
  }
.progress {
  width: 100%;
  height: 30px;
  background-color: silver;
}

.bar-one {
  background-color: blue;
}

.bar-two {
  background-color: red;
}
<script src="http://ift.tt/1oMJErh"></script>
<div class="progress">
    <div class="bar-one" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100">
    </div>
</div>
<br>
<div class="progress">
    <div class="bar-two" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100">
    </div>
</div>
<br>
<div id="panel">
    <input type="checkbox" value1="20" value2="5">
    <input type="checkbox" value1="5" value2="20">
    <input type="checkbox" value1="10" value2="10">
    <input type="checkbox" value1="10" value2="-20">
    <input type="checkbox" value1="-20" value2="10">

</div>

<div class="even">
  Pressure is ok
</div>
<div class="high">
  Pressure is high
</div>
<div class="low">
  pressure is low
</div>

Your help is really appreciated!




pass value from MVC View to MVC Controller depending on checkbox checked

in a MVC C# View I show the records of specifics employees, for that I use MVCScaffolding and the model below

 public class Developer
    {
        public int code { get; set; }
        public string areaDev { get; set; }
        public string nameDev { get; set; }
        public string expDev { get; set; }
        public string langDev { get; set; }
    }

the view uses razor and for every record there is a checkbox input

@model IEnumerable<WebApplication1.Models.Developer>

@using(Html.BeginForm("ShowRecords","Home"))
{

<table class="table">
    <tr>
        <th>@Html.DisplayNameFor(model => model.code)</th>
        <th>@Html.DisplayNameFor(model => model.areaDev)</th>
        <th>@Html.DisplayNameFor(model => model.nameDev)</th>
        <th>@Html.DisplayNameFor(model => model.expDev)</th>
        <th>@Html.DisplayNameFor(model => model.langDev)</th>
        <th>select</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>@Html.DisplayFor(modelItem => item.code)</td>
        <td>@Html.DisplayFor(modelItem => item.areaDev)</td>
        <td>@Html.DisplayFor(modelItem => item.nameDev)</td>
        <td>@Html.DisplayFor(modelItem => item.expDev)</td>
        <td>@Html.DisplayFor(modelItem => item.langDev)</td>
        <td><input type="checkbox" name="code" value="@item.code" /></td>
    </tr>
}
</table>
<input type="submit" value="SEND" />
}

and what I want is to retrieve the information of code(integer code) when the user click the checkbox of one/many specific records displayed in the view,

enter image description here

for that in my controller I receive a int[] as shown below

  public ActionResult ShowRecords(int[] datos)
    {
        {
            foreach(var item in datos)  
            {  ... some code goes here ... }     
            return View(); 
        }

But I don't receive anything from the view, always receive NULL

enter image description here

could you please help me and tell how to retrieve the code info of the due checked row in my controller?




$.ajax doesn't work the first time

I'm trying to filter a research thanks to some checkboxes. When i click on a checkbox an Ajax call is sent from "lista.php" to "filtro.php". Here's there's a a new query that print into the while loop of "lista.php" a div with class ".singoloRisultato" that overwrite the old foreach loop. The problem is that the Ajax call doesn't work the first time but it starts to work on the second time. Here's the code!

This is one of the checkboxes inside "Lista.php". They're all the same.

<section>
        <h5><span class="glyphicon glyphicon-signal"></span> Free Wi-Fi</h5>
         <div class="filter">
           <span class="glyphicon glyphicon-signal"></span>
           <input type="checkbox" value="1" id="wifi" name="wifi" />
           <label for="wifi"></label>
         </div>
</section>

This is the code inside the foreach loop inside "Lista.php"

<div class="singoloRisultato">
 <a href="<?php echo $row[4] ?>">
 <div class="col-sm-3 col-xs-12">
       <img src="img/<?php echo $row[3] ?>" />
 </div>
     <div class="col-sm-6 col-xs-12 nomeLista">
       <h3><?php echo $row[1] ?></h3>
       <p>
        <div class="rating">
            <p>Voto medio: <b><?php echo round($row[19], 1) ?><sub>/5</sub></b></p>
         </div>
       </p>
       <p>
         <span class="glyphicon glyphicon-map-marker"></span> <?php echo $row[11] ?>
       </p><br />
       <p>
         <em><?php echo $row[2] ?></em>
       </p>
     </div>
     <div class="col-sm-3 col-xs-12 text-center" style="line-height: 200px">
       <button class="btn btn-warning">Scopri <span class="glyphicon glyphicon-menu-right"></span></button>
     </div>
       </a>
   </div>

And this is the Ajax in "Lista.php"

$(document).ready(function(){
   $("input:checkbox").change(function() {
  function getEmployeeFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.name);
}
});
return opts;
}

var $checkboxes = $("input:checkbox");
$("input:checkbox").off();
$checkboxes.on("change", function(){
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
updateEmployees();

function updateEmployees(opts){
$.ajax({
async: true,
type: "POST",
url: "filtro.php",
dataType : '',
cache: false,
data: {filterOpts: opts},
success: function(records){
  console.log('script loaded');

$('.risultatoLista .risultato').html(records);
}
});


}

 });

  });

Finally, this is "filtro.php"

$select = "SELECT SQL_CALC_FOUND_ROWS *, AVG(recensioni_scuole.voto) AS voto";
$from = " FROM scuole INNER JOIN zona ON scuole.id_quartiere=zona.id_quartiere LEFT JOIN recensioni_scuole ON scuole.id=recensioni_scuole.id";
$where = " WHERE TRUE AND zona.id_quartiere=1";
$groupby = " GROUP BY scuole.id";

$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');

if (in_array("wifi", $opts)){
$where .= " AND wifi = 1";
}

if (in_array("registrazione", $opts)){
$where .= " AND registrazione = 1";
}
if (in_array("parcheggio", $opts)){
$where .= " AND parcheggio = 1";
}
if (in_array("disabili", $opts)){
$where .= " AND disabili = 1";
}
if (in_array("voto1", $opts)){
$where .= " AND voto > 0.9";
}
if (in_array("voto2", $opts)){
$where .= " AND voto > 1.9";
}
if (in_array("voto3", $opts)){
$where .= " AND voto > 2.9";
}
if (in_array("voto4", $opts)){
$where .= " AND voto > 3.9";
}
if (in_array("voto5", $opts)){
$where .= " AND voto > 4.9";
}
var_dump($opts);
$sqlFiltro = $select . $from . $where . $groupby;
$stmtFiltro = $dbh->prepare($sqlFiltro);
$stmtFiltro->execute(array($quartiere));
$res = $stmtFiltro->fetchAll(PDO::FETCH_ASSOC);
echo $sqlFiltro;
 foreach ($res as $row) { ?>

   <div class="singoloRisultato">
      <a href="<?php echo $row['link'] ?>">
      <div class="col-sm-3 col-xs-12">
            <img src="img/<?php echo $row['img'] ?>" />
      </div>
          <div class="col-sm-6 col-xs-12 nomeLista">
            <h3><?php echo $row['nome'] ?></h3>
            <p>
             <div class="rating">
                 <p>Voto medio: <b><?php echo round($row['voto'], 1) ?><sub>/5</sub></b></p>
              </div>
            </p>
            <p>
              <span class="glyphicon glyphicon-map-marker"></span> <?php echo $row['nomeQuartiere'] ?>
            </p><br />
            <p>
              <em><?php echo $row['descrizione'] ?></em>
            </p>
          </div>
          <div class="col-sm-3 col-xs-12 text-center" style="line-height: 200px">
            <button class="btn btn-warning">Scopri <span class="glyphicon glyphicon-menu-right"></span></button>
          </div>
            </a>
        </div>


 <?php }

 $stmtFiltro->closeCursor();
 unset($dbh);
 }

Do you know why this is working fine except for the first time that i check a checkbox? Thank you for your help!!




angularjs checkbox with ng-repeat

i want to make something like this angularjs-checkbox

this is my code

<script src="http://ift.tt/1mQ03rn"></script>
<!DOCTYPE html>
<html lang="en">
<head></head>
<script>
  var app = angular.module("myApp", []);
  app.controller("myCtrl", function($scope) {
    $scope.records = [
      "ALL",
      "KOREAN",
      "ENGLISH",
      "CHINESE",
      "JAPANESE",
      "GERMAN",
      "FRENCH",
      "ITALIAN",
      "SPANISH",
      "OTHERS",
    ]
  });
</script>

<body class="other_page" ng-app="myApp">
  <table class="checkbox_table" ng-controller="myCtrl">
    <tr>
      <td colspan="3" class="filter_subtitle_td">
        <div class="filter_subtitle">
          <span>
            CATEGORY
          </span>
        </div>
      </td>
    </tr>
    <tr ng-repeat="x in records" ng-if="$index % 3 == 0">
      <td class="checkbox_td">
        <input type="checkbox" id="" class="category_filter_checkbox" ng-model="all" />
        <label for="" class="checkbox_label">
          
        </label>
      </td>
      <td class="checkbox_td" ng-if="x != ''">
        <input type="checkbox" id="" class="category_filter_checkbox" ng-checked="all" />
        <label for="" class="checkbox_label">
          
        </label>
      </td>
      <td class="checkbox_td" ng-if="x != ''">
        <input type="checkbox" id="" class="category_filter_checkbox" ng-checked="all" />
        <label for="" class="checkbox_label">
          
        </label>
      </td>
    </tr>
  </table>
</body>

</html>

my questions is: 1. how to make ng-repeat stop when no data left?
2. how to give only 'ALL' data ng-model so the other checkbox can be selected by click this 'ALL' checkbox?

Thank you for your help




how to set textbox width using javascript with checkbox checked

    $(function () {
        $("#chkShowPassword").bind("click", function () {

            var loginPW = $("[id*=loginPW]");

            if ($(this).is(":checked")) {


                loginPW.after('<input id = "txt_' + loginPW.attr("id") + '" type = "text" value = "' + loginPW.val() + '" />');
                loginPW.hide();
            } else {
                loginPW.val(loginPW.next().val());

                loginPW.next().remove();
                loginPW.show();
            }
        });
    });

here is the text box:

 <asp:TextBox CssClass="txtInput col-1" ID="loginPW" runat="server" TextMode="Password"></asp:TextBox>

and the checkbox is:

<asp:CheckBox ID="chkShowPassword" runat="server" Text="ShowPassword" />

suppose if the width of the text box is 100px, with the checkbox checked the textmode changes to singleline , but the width sets to the basic or default px.I tried with document.getelementbyid ... didn't worked .




Reset radio buttons when unchecking checkbox in AngularJS

example

In the example above, the radio buttons below the checkbox are activated when the checkbox is checked. I'd like to reset the radio buttons (so that no radio button is filled) when unchecking this checkbox.

<div class="checkbox checkbox-info">
  <input id="icb" type="checkbox" ng-model="checked">
  <label for="icb"><i class="fa fa-refresh">&nbsp;</i><b>Integratie</b></label>
</div>
<div class="radio">
  <input type="radio" name="irb" id="iarb" ng-disabled="!checked" value="!checked">
  <label for="iarb">Administrator</label>
</div>
<div class="radio">
  <input type="radio" name="irb" id="imrb" ng-disabled="!checked" value="!checked">
  <label for="imrb">Medewerker</label>
</div>



How to create true or false checkbox in Yii2?

I have a problem here. In my ActiveForm I need to create a simple checkbox (which has to be a boolean value (0 - if the item was unpaid and 1 - if it was paid).

I've created in my view file a checkbox like this:

<?= $form->field($model, 'sign')->checkboxList([
    '' => '',
]); ?>

I thought that if I will mark the checkbox it will automatically will change to 1 (because in the database the value was set was boolean), but now it's writing that it must be an integer. When I'm deleting my rule and submitting my form, that value in the database is NULL.

So could anyone tell me how to do a checkbox, which if I would mark it, the value in the database would be 1, otherwise - 0? Thank you for any help..




CodeIgniter Marking checkboxes from database

I want to repopulate a page that contains checkboxes from values in the database. Currently, they are being stored as a string that gets split into an array when processing e.g 3,4,5.

I am able to check the boxes with the data from my database but another empty checkbox is created by its side. How do I only check the boxes with data from the database without having a duplicate empty box by its side?

<tbody>               
       <?php 
           if(!empty($datatable)){
              foreach ($datatable as $data){
        ?>
                    <tr>
                        <td>
                            <?php foreach ($event_contacts as $checked){?>
                                <?php if($checked==$data->id){?>
                                    <input type="checkbox" name="id[]" id="id" checked value="<?php echo $data->id; ?>"/>
                            <?php }else{ ?>
                                    <input type="checkbox" name="id[]" id="id" value="<?php echo $data->id; ?>"/>
                            <?php }}?>
                        </td>
                        <td><?php echo $data->first_name." ".$data->last_name; ?></td>
                        <td><?php echo $data->email; ?></td>
                        <td><?php echo $data->phone_number; ?></td>
                        <td><?php echo $data->address;?></td>
                    </tr>
                <?php 
                    }
                }
                ?>
            </tbody>

Hope someone can help. Thanks

EDIT: Added photo for clarity

enter image description here




samedi 29 avril 2017

Copying an element's html content using Jquery to another element, not working for checkbox status (checked, unchecked) ?

This is my simple html page :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="jquery.min.js"></script>
    <script >
      function copy(){
         $("#two").html($("#one").html());
      }
    </script>
</head>
<body>

<button onclick="copy()">copy</button>

<div id="one">
<input type="checkbox" name="test" >
</div>

<div id="two">
</div>


</body>
</html>

when I click the button, contents of div#one is copied to div#two, but when I first click on checkbox (It is checked now!) and then click the Button, The second checkbox is produced, but it is not checked!! why?




document.getElementsByClassName('')[i].addEventListener('click', function() {};) EventListener only executes on the last element of the array?

I am using Js to enable a form field when a checkbox is check otherwise its disable. I am using document.getElementsByClassName which returns an array of checkboxes then i add an addEventListener to each through a for loop. I then check if the box is checked and either removeAttribute('diabled') or setAttribute of a target form field which i get from the href of the checkbox. everything works great except that it only works for the element of the getElementsByClassName array.

html code:

<div class="form-group">
    <form method="POST" action="/admin_accounts/editaccount.php">
        <div class="input-group">
            <div class="input-group-addon input-group-addon-reponsive">
                <label for="memType">Member Type</label>
            </div>
            <select class="form-control" id="memTypeEdit" name="memTypeEdit" disabled>
                <option value="Regular">Regular</option>
                <option value="Ordinary">Ordinary</option>
                <option value="Associate">Associate</option>
                <option value="Executive">Executive</option>
                <option value="Honorary">Honorary</option>
                <option value="Dependant">Dependant</option>
                <option value="Instructor">Instructor</option>
                <option value="Volunteer">Volunteer</option>
            </select>
            <div class="input-group-addon"> 
                <input type="checkbox" class="edit-toggle" href="memTypeEdit"> 
                <label>Edit</label>
            </div>
        </div> 
        <div class="input-group">
            <div class="input-group-addon input-group-addon-reponsive">
                <label for="employ">Employment</label>
            </div>
            <select class="form-control" id="employEdit" name="employEdit" disabled>
                <option value="None"              >None</option>
                <option value="President"         >President</option>
                <option value="Vice President"    >Vice President</option>
                <option value="Treasurer"         >Treasurer</option>
                <option value="Clerk"             >Clerk</option>
                <option value="Instructor"        >Instructor</option>
                <option value="Web Administrator" >Web Administrator</option>
                <option value=""                  >Volunteer</option>
            </select>
            <div class="input-group-addon"> 
                <input type="checkbox" class="edit-toggle" href="employEdit"> 
                <label>Edit</label>  
            </div>
        </div>
        <div class="input-group date" data-provide="datepicker">
            <div class="input-group-addon input-group-addon-reponsive">
                <label for="regDate">Registration Date</label>
            </div>
            <input type="text" id="regDateEdit" name="regDateEdit" class="form-control" disabled>
            <div class="input-group-addon">
                <input type="checkbox" class="edit-toggle" href="regDateEdit"> 
                <label>Edit</label>
            </div>
        </div>
        <div class="input-group date" data-provide="datepicker">
            <div class="input-group-addon input-group-addon-reponsive">
                <label for="expDate">Expiry Date</label>
            </div>
            <input type="text" class="form-control" id="expDateEdit" name="expDateEdit" disabled>
            <div class="input-group-addon">
                <input type="checkbox" class="edit-toggle" href="expDateEdit"> 
                <label>Edit</label>
            </div>
        </div>
        <div class="input-group">
            <div class="input-group-addon input-group-addon-reponsive">
                <label for="admin">Administrator</label>
            </div>
            <select class="form-control" id="adminEdit" name="adminEdit" disabled>
                <option value="0">Is Not Administrator</option>
                <option value="1">Is Administrator</option>                                        
            </select>
            <div class="input-group-addon"> 
                <input type="checkbox" class="edit-toggle" href="adminEdit"> 
                <label>Edit</label>
            </div>                                                        
        </div>
        <div class="text-right">
            <div class="btn-group btn-group-sm" role="group">
                <button type="submit" name="create" class="btn btn-success">Save</button>
                <button type="reset" class="btn btn-info" value="Reset">Reset</button>
            </div> 
        </div>
    </form>
</div>

and the Js:

<script>
    var anchors = document.getElementsByClassName('edit-toggle');
    for (var i = 0, length = anchors.length; i < length; i++) {
        var anchor = anchors[i];
        anchor.addEventListener('click', function() {
            var target = document.getElementById(anchor.getAttribute('href'));
            if (anchor.checked){
                target.removeAttribute('disabled');
            }else{
                target.setAttribute('disabled', 'disabled');
            }
        }, true);
    };
</script>

As it is right now the name="adminEdit" works as intended but non of the others but when I remove class="edit-toggle" from the adminEdit checkbox, the expDateEdit starts working. So it looks like on the last element works. any ideas? thank you.




Checkbox Bootstrap data toggle not rendering on click in JqueryDataTable in Mobile Browser View

Currently I have a jquery datatable in which I added checkbox column using bootstrap data-toggle, when I open in my PC browser, I can able to toggle the data-toggle checkbox but same thing not working in mobile browser view.

jsp code snippet as below:

    $(document).ready(function(){
        var searchCondition = '${searchCondition}';

        $('#dtable').DataTable({
                "bAutoWidth": true,
                "order": [[ 0, "asc" ]],
            "lengthMenu": [[10,20,30,50, -1], [10,20,30,50, "All"]],
            "oSearch" : {"sSearch": searchCondition},
            responsive: true
        });
    });
<%@ taglib prefix="form" uri="http://ift.tt/IED0jK" %>
<%@ taglib prefix="spring" uri="http://ift.tt/18bwTB1" %>
<%@ include file="/WEB-INF/views/template/header.jsp" %>

<div class="container-wrapper">
    <div class="container">
        <div class="page-header alert alert-success">
            <h1>Customer Management Page</h1>

            <p class="lead">This is the customer management page!</p>
        </div>
<form:form method="post" action="${pageContext.request.contextPath}/admin/updateAdminCustomer" modelAttribute="customerManagmentUtilForm">
        <table id="dtable" class="datatable table-striped table-hover display">
            <thead>
            <tr class="bg-primary">
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Username</th>
                <th>Customer Type</th>
                <th>Enabled</th>
            </tr>
            </thead>
            <tfoot>
            <tr class="bg-primary">
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Username</th>
                <th>Customer Type</th>
                <th>Enabled</th>
            </tr>
            </tfoot>
            
            <tbody>
            <c:forEach items="${customerManagmentUtilForm.customerManagmentUtilList}" var="custMgmt" varStatus="status">
                <tr>
                        <%-- <td align="center"><form:hidden path="customerManagmentUtilList[${status.index}].customerId"  name="customerManagmentList[${status.index}].customerId" value="${custMgmt.customerId}" placeholder="Readonly input" readonly="readonly"/>${status.count}</td> --%>
                        
                        <td>${custMgmt.customerName}
                        <form:hidden path="customerManagmentUtilList[${status.index}].customerName"  name="customerManagmentList[${status.index}].customerName" value="${custMgmt.customerName}" placeholder="Readonly input" readonly="readonly"/>
                        <form:hidden path="customerManagmentUtilList[${status.index}].customerId"  name="customerManagmentList[${status.index}].customerId" value="${custMgmt.customerId}" placeholder="Readonly input" readonly="readonly"/>
                        </td>
                        <td>${custMgmt.customerEmail}<form:hidden path="customerManagmentUtilList[${status.index}].customerEmail" name="customerManagmentList[${status.index}].customerEmail" value="${custMgmt.customerEmail}" placeholder="Readonly input" readonly="readonly"/></td>
                        <td>${custMgmt.customerPhone}<form:hidden path="customerManagmentUtilList[${status.index}].customerPhone" name="customerManagmentList[${status.index}].customerPhone" value="${custMgmt.customerPhone}" placeholder="Readonly input" readonly="readonly"/></td>
                        <td>${custMgmt.userName}<form:hidden path="customerManagmentUtilList[${status.index}].userName" name="customerManagmentList[${status.index}].userName" value="${custMgmt.userName}" placeholder="Readonly input" readonly="readonly"/></td>
                        <td>${custMgmt.customerRole}<form:hidden path="customerManagmentUtilList[${status.index}].customerRole" name="customerManagmentList[${status.index}].customerRole" value="${custMgmt.customerRole}" placeholder="Readonly input" readonly="readonly"/></td>
                        <td><form:checkbox id="toggle-two" path="customerManagmentUtilList[${status.index}].enable" name="customerManagmentList[${status.index}].enable" value="${custMgmt.enable}" data-toggle="toggle" data-onstyle="success" data-offstyle="danger" data-on="Enabled" data-off="Disabled"/></td>
                        
                </tr>

        </c:forEach>
        </tbody>
        </table>
        <input type="submit" value="submit" class="btn btn-default">
        <a href="<c:url value="/admin" />" class="btn btn-default">Cancel</a>
        
</form:form>
<%@ include file="/WEB-INF/views/template/footer.jsp" %>

PC browser image(Initial State, OK) Initial State in PC Browser OK PC browser image(After toggle State, OK) After toggle State in PC Browser OK Mobile View in Browser(Can't not Toggle when click, NOT OK) Mobile View in Browser Can't not Toggle Kindly help me where do I need to fix.

Thank you very much.




iOS swift 3 after checkbox is checked select label name

How would one go about selecting the text from a label name after checking a nearby checkbox? Say you place a label named "Whole Wheat" next to a checkbox and when the image in the checkbox changes to checked, the text from the label -- WholeWheat -- would be stored in a variable or otherwise be made available for use elsewhere.

Mostly know how to retrieve values from labels and textfields, just not by limiting selections to those associated with checked boxes.

Steps taken so far include creating standard checkbox class with checked and unchecked image, adding various functions such as

func configure(_ label: String) {

and

a couple renditions of isSelected,

and placing print statements everywhere imaginable, all with nil outcomes or worse. Using Xcode 8.3.1 and Swift 3. Any help would be much appreciated.




PrimeNg Checkbox execute function

I've been trying to get a function to happen whenever I press a checkbox in a datatable. Basically what I have is a datatable with default values in it (1 to 10 for example). Then I give an array of items to my component which are present in an object of mine (2 & 5 for example). now when the grid is constructed It'll all the default elements in the dataTable but Only the data that is in our object will have a checked checkbox next to them. Now what I want to do is to have my addOrRemove function executed wich depending on the state of the checkbox will add or remove a default data object from the array ([2,5] in this case). So 2 or 5 can be unchecked and thus removed from the array and 1,3,4,6,7,8,9,10 can be checked and added to the array.

I don't realy have a problem writing the code for this but I'm struggling to have my function being executed whenever I press the checkbox.

this is how I have my checkbox defined in my html file:

<p-column header="Included" [style]="{'width':'80px', 'text-align':'center'}">
    <template let-object="rowData" pTemplate="body">
        <p-checkbox binary="true" [(ngModel)]="object.included" (change)="addOrRemoveRow($event,object.data)"></p-checkbox>
    </template>
</p-column>

using this I'm not getting any functions triggered. In the PrimeNg documentation there is stated that p-checkbox has an event onChange. but whenever I use that I'm getting the error.

EXCEPTION: Error in http://localhost:3000/app/shared/grid/checkable-grid/checkable-grid.component.html:9:12 caused by:
 self.parentView.context.addOrRemoveRow is not a function

That is whenever I change the (change) to (onChange).

I've read that it has something to do with my checkbox being inside of a template and therefore there is no direct access to my component and its functions. Any help on this would be much appreciated.




Calculate the total of form immediately without having to check a checkbox

I have an HTML, JavaScript form, which calculates a price based upon choices made in the form. The problem is that the total price will only be calculated after one checkbox has been clicked. I want it to calculate the price immediately without having to check a checkbox first. Below is a snippet of the JavaScript code:

function totalIt() {
  var input = document.getElementsByName("product");
  var total = 0;
  for (var i = 0; i < input.length; i++) {
    if (input[i].checked) {
        total += parseFloat(input[i].value); // this function should run immediately
    }
  }
  document.getElementById("total").value = "€" + total.toFixed(2);
}

The full form can be found here.

How can this be done?




Django form checkbox unable to save data

I am trying to display a form (with multiple select checkbox) and save the data in database. But having some problem.

Here is My Model:-

class Preference(models.Model):
CLASS_CHOICES = [('1', '1'), ('2', '2'), ('3', '3')]
BOARD_CHOICES = [('C', 'CBSE'), ('I', 'ICSE'), ('S', 'State Board')]
SUBJECT_CHOICES = [('H', 'HINDI'), ('M', 'MATH'), ('E', 'ENGLISH')]
Class = models.CharField(max_length=2, choices=CLASS_CHOICES, default='1', 
blank=False)
Board = models.CharField(max_length=2, choices=BOARD_CHOICES, default='C', 
blank=False)
Subject = models.CharField(max_length=2, choices=SUBJECT_CHOICES, 
default='M', blank=False)

My form:-

class PreferenceForm(forms.ModelForm):
    class Meta:
    model = Preference
    fields = ['Class', 'Board', 'Subject']
    widgets = {
           'Board': forms.RadioSelect(),
           'Subject': forms.CheckboxSelectMultiple  } 

My View:-

def pref2(request):
    form = PreferenceForm(request.POST or None)
    if form.is_valid():
        form.save()
        return render(request, 'website/thanks.html')
    else:
        print(form.errors)
        return render(request, 'website/pref2.html', {'form': form})

It displays the checkbox but I am unable to save that data to database even when I select a single choice. It displays the error:- `

<ul class="errorlist"><li>Subject<ul class="errorlist"><li>Select a valid choice. [&#39;H&#39;, &#39;M&#39;] is not one of the available choices.</li></ul></li></ul>

All help/suggestions are appreciated, thanks.

`




Call 2 JavaScript functions for one checkbox

I've got a little problem, my checkbox already has an ID, Name etc. attached to it, so I don't know how to link the JavaScript code below to the checkbox, because the ID and Name are already used. I already know that you cannot use multiple IDs, because it will then only use the first ID specified.

Any ideas how to fix this?

setTimeout(function(){
document.getElementById('checkboxdelay').checked = true;
},1000)
<input name="product" value="199" type="checkbox" id="p4" id="checkboxdelay" onChange="totalIt()"/>



Have checkbox be checked with delay

I have a simple question: How can you have a checkbox be checked automatically (as already shown in the code snippet), but with a delay of 100ms? So that when you load the page, after 100ms the checkbox gets checked (and will stay checked). I think you need JavaScript for it, but I don't know how to do it.

<input checked type="checkbox"/>

Any ideas for a clean and good way to achieve this?




Checked checkbox background not working

I have used background color for checked checkbox through jQuery. My background color is adding only if i click any checkbox but not already clicked checkbox by default & i don't know why my class is not working on clicked checkbox by default.

$(document).ready(function() {
  /*checkbox-background*/
  $(".checkbox-primary").on("click", "input[type='checkbox']", function() {
    if ($(this).is(":checked")) {
      $(this).parent().addClass("fltr-chk-box-bg");
    } else {
      $(this).parent().removeClass("fltr-chk-box-bg");
    }
  });
  /*checkbox-background-ends*/
});
.checkbox {
  padding-left: 30px;
}

.checkbox>label {
  display: inline-block;
  position: relative;
  padding-left: 5px;
  color: #686868;
  padding-top: 2px;
  min-height: 25px;
  font-family: 'montserrat';
}

.checkbox>span {
  padding-right: 17px;
  padding-top: 3px;
  font-family: 'montserrat';
}
.checkbox input[type="checkbox"]:disabled+label::before {
  background-color: #eeeeee;
  cursor: not-allowed;
}

.checkbox.checkbox-circle label::before {
  border-radius: 50%;
}

.checkbox.checkbox-inline {
  margin-top: 0;
}

.fltr-chk-box-bg {
  background-color: #E3E7EA;
  color: #1E6C97;
}

.checkbox-primary input[type="checkbox"]:checked+label::before {
  background-color: #1E6C97;
  border-color: #428bca;
}

.checkbox-primary input[type="checkbox"]:checked+label::after {
  color: #fff;
}

.checkbox input[type="checkbox"]:checked+label+span {
  position: relative;
  z-index: 75456;
}

.checkbox input[type="checkbox"]:checked+label+span:before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  border-bottom: 13px solid #CCD2D6;
  border-top: 11px solid #CCD2D6;
  border-right: 50px solid #CCD2D6;
  border-left: 6px solid transparent;
  z-index: -7523;
}

.fltr-panel-group {
  margin-bottom: 0px;
}

.fltr-panel {
  border-bottom: none;
}

.fltr-panel:last-child {
  border-bottom: 1px solid #ddd;
}

.fltr-panel-title>a {
  padding: 18px 8px 19px 8px;
  font-size: 1.21em;
  color: #2B3439;
  font-family: 'montserrat';
}

.panel-group .panel+.panel.fltr-panel {
  margin-top: 0px;
}

.panel-group.fltr-panel-group .panel-heading+.panel-collapse>.panel-body.fltr-panel-body {
  border-top: none;
  padding: 0px 5px 5px 5px;
}

.fltr-and-reset {
  padding-top: 14px;
  padding-bottom: 5px;
}

.fltr-and-reset a {
  vertical-align: middle;
  font-size: 0.78em;
}

.fltr-and-reset>.pull-right {
  font-size: 1.07em;
  color: #1E6C97;
  font-family: 'montserrat';
}

.fltr-and-reset>.text-left {
  font-size: 1.14em;
  color: #302F2F;
  line-height: 1.647;
  font-family: 'montserrat';
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://ift.tt/2apRjw3">

<!-- jQuery library -->
<script src="http://ift.tt/2nYZfvi"></script>

<!-- Latest compiled JavaScript -->
<script src="http://ift.tt/2aHTozy"></script>
<form>
  <div class="checkbox checkbox-primary">
    <input type="checkbox" value="" checked>
    <label>North America</label><span class="pull-right">75</span>
  </div>
  <div class="checkbox checkbox-primary">
    <input type="checkbox" value="" checked>
    <label>South America</label><span class="pull-right">98</span>
  </div>
  <div class="checkbox checkbox-primary">
    <input type="checkbox" value="">
    <label>North America</label><span class="pull-right">23</span>
  </div>
  <div class="checkbox checkbox-primary">
    <input type="checkbox" value="">
    <label>South Asia</label><span class="pull-right">47</span>
  </div>
  <div class="checkbox checkbox-primary">
    <input type="checkbox" value="">
    <label>South America</label><span class="pull-right">53</span>
  </div>
  <div class="checkbox checkbox-primary">
    <input type="checkbox" value="">
    <label>North America</label><span class="pull-right">55</span>
  </div>
  <div class="checkbox checkbox-primary">
    <input type="checkbox" value="">
    <label>South America</label><span class="pull-right">26</span>
  </div>
  <div class="checkbox checkbox-primary">
    <input type="checkbox" value="">
    <label>North America</label><span class="pull-right">23</span>
  </div>
  <div class="checkbox checkbox-primary">
    <input type="checkbox" value="">
    <label>South America</label><span class="pull-right">78</span>
  </div>
  <div class="checkbox checkbox-primary">
    <input type="checkbox" value="">
    <label>South America</label><span class="pull-right">90</span>
  </div>
  <div class="checkbox checkbox-primary">
    <input type="checkbox" value="">
    <label>North America</label><span class="pull-right">67</span>
  </div>
  <div class="checkbox checkbox-primary">
    <input type="checkbox" value="">
    <label>South America</label><span class="pull-right">88</span>
  </div>
</form>



Razor Mvc Only one checkbox selected

I am using MVC 5,razor,C# and in the view i have 4 checkboxes for each question and must select only 1 checkbox for each question. I must use Javascript to be able to do this and how I can do it?

 for (var i = 0; i < Model.Count; i++)
    {
        @Html.DisplayFor(model => model[i].QuestionTx)
        @Html.HiddenFor(model => model[i].Id)
        @Html.HiddenFor(model => model[i].ClassTestId)
        @Html.HiddenFor(model => model[i].QueastionMarksInt)
        <br />
        <br />
        for (var o = 0; o < Model[i].ClassTestQuestionMc.Count; o++)
        {
          @Html.DisplayFor(model => Model[i].ClassTestQuestionMc[o].AnswerTx)
            @Html.CheckBoxFor(model => Model[i].ClassTestQuestionMc[o].IsChecked) 
              @Html.HiddenFor(model => Model[i].ClassTestQuestionMc[o].AnswerTx)
            @Html.HiddenFor(model => Model[i].ClassTestQuestionMc[o].IsChecked)
            @Html.HiddenFor(model => Model[i].ClassTestQuestionMc[o].Id)
            @Html.HiddenFor(model => Model[i].ClassTestQuestionMc[o].IsCorrectAnswer)

        }
        <br />
        <br />
        <br />
    }




vendredi 28 avril 2017

HTML Checkbox cannot be checked

I have some checkbox in a table that contains the id of that row item. I want to allow the user to select multiple rows. However, I can't seem to check the checkbox on Chrome. I loaded the site up on my mobile and it works. I have tried to insert an onclick but it doesn't seem like the checkbox is registering any clicks to it as well. Please help.

The table

<table class="table">
            <thead>
                <tr class="text-left">
                    <td></td>
                    <td>Name</td>
                    <td>Email</td>
                    <td>Phone Number</td>
                    <td>Address</td>
                </tr>
            </thead>
            <tbody>
                <?php 
                    if(!empty($datatable)){
                        foreach ($datatable as $data){
                ?>
                    <tr>
                        <td><input type="checkbox" name="id[]" value="<?php echo $data->id; ?>"/></td>
                        <td><?php echo $data->first_name." ".$data->last_name; ?></td>
                        <td><?php echo $data->email; ?></td>
                        <td><?php echo $data->phone_number; ?></td>
                        <td><?php echo $data->address;?></td>
                    </tr>
                <?php 
                    }
                }
                ?>
            </tbody>
        </table>

EDIT: I have cleared my cache and cookies as well. It works on the mobile but not on chrome for some reason.




NatTable with checkbox column - check/uncheck not working

Used EditableGrid example to create a checkbox column inside my NatTable, however the mouse events to check and uncheck are not getting triggered and hence the state of checkbox doesn't change. Below is the code snippet:

private Control exampleNatTableWithCheckBox(Composite parent) {

        final String[] propertyNames = PLAN_PROPERTY_NAMES;
        final Map<String, String> propertyToLabelMap = getPropertyToLabelMap();

        IRowIdAccessor<ConsoleEntry> rowIdAccessor = new IRowIdAccessor<T>() {
            @Override
            public Serializable getRowId(T rowObject) {
                return rowObject.getRcdIdx();
            }
        };
        ConfigRegistry configRegistry = new ConfigRegistry();

        // Body
        this.baseEventList = getBaseEventList();
        FilterList<T> filterList = new FilterList<T>(baseEventList);
        SortedList<T> sortedList = new SortedList<T>(filterList, null);

        bodyLayer = new FullFeaturedBodyStackLayer<ConsoleEntry>(sortedList, rowIdAccessor, propertyNames,configRegistry);

        this.bodyDataProvider = bodyLayer.getBodyDataProvider();

        registerConfigCells(configRegistry);

        registerCheckBoxEditor(configRegistry);

        // Column header
        FullFeaturedColumnHeaderLayerStack<T> columnHeaderLayer = new FullFeaturedColumnHeaderLayerStack<T>(sortedList, filterList, propertyNames, propertyToLabelMap, bodyLayer, bodyLayer.getSelectionLayer(),
                configRegistry);

        // Row header
        final DefaultRowHeaderDataProvider rowHeaderDataProvider = new DefaultSummaryRowHeaderDataProvider(
                this.bodyDataProvider);
        DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
        rowHeaderDataLayer.setDefaultColumnWidth(50);
        ILayer rowHeaderLayer = new RowHeaderLayer(rowHeaderDataLayer, bodyLayer, bodyLayer.getSelectionLayer());

        // Corner
        final DefaultCornerDataProvider cornerDataProvider = new DefaultCornerDataProvider(
                columnHeaderLayer.getColumnHeaderDataProvider(), rowHeaderDataProvider);
        DataLayer cornerDataLayer = new DataLayer(cornerDataProvider);
        ILayer cornerLayer = new CornerLayer(cornerDataLayer, rowHeaderLayer, columnHeaderLayer);

        // Grid
        GridLayer gridLayer = new GridLayer(bodyLayer, columnHeaderLayer, rowHeaderLayer, cornerLayer);

        this.natTable = new NatTable(parent, gridLayer, false);

        this.natTable.setConfigRegistry(configRegistry);

        this.natTable.addConfiguration(new StyledRowHeaderConfiguration());
        this.natTable.addConfiguration(new StyledColumnHeaderConfiguration());
        this.natTable.addConfiguration(new DefaultNatTableStyleConfiguration());

        // Popup menu
        this.natTable.addConfiguration(new HeaderMenuConfiguration(this.natTable) {
            @Override
            protected PopupMenuBuilder createColumnHeaderMenu(NatTable natTable) {
                return super.createColumnHeaderMenu(natTable).withColumnChooserMenuItem();
            }
        });

        this.natTable.addConfiguration(new SingleClickSortConfiguration());

        // Editing
        ColumnOverrideLabelAccumulator columnLabelAccumulator = new ColumnOverrideLabelAccumulator(
                bodyLayer.getBodyDataLayer());
        bodyLayer.getBodyDataLayer().setConfigLabelAccumulator(columnLabelAccumulator);
        columnLabelAccumulator.registerColumnOverrides(0, COLUMN_BOOKMARK_LABEL);

        this.natTable.addConfiguration(editableGridConfiguration(columnLabelAccumulator, this.bodyDataProvider));
        this.natTable.addConfiguration(filterRowConfiguration());

        bodyLayer.getBodyDataLayer().setConfigLabelAccumulator(getConfigLabelAccumulator(bodyLayer.getBodyDataLayer()));

        // Preserve selection on updates and sort
        final SelectionLayer selectionLayer = bodyLayer.getSelectionLayer();
        final RowSelectionModel<ConsoleEntry> rowSelectionModel = new RowSelectionModel<ConsoleEntry>(selectionLayer,
                this.bodyDataProvider, rowIdAccessor);
        selectionLayer.setSelectionModel(rowSelectionModel);

        // Select complete rows
        RowOnlySelectionConfiguration<ConsoleEntry> selectionConfig = new RowOnlySelectionConfiguration<ConsoleEntry>();
        selectionLayer.addConfiguration(selectionConfig);
//      this.natTable.addConfiguration(new RowOnlySelectionBindings());

         rowSelectionProviderNatTable = new RowSelectionProvider<ConsoleEntry>(selectionLayer,
                this.bodyDataProvider);
        if (this.bodyDataProvider.getList() != null && this.bodyDataProvider.getList().size() > 0) {
            rowSelectionProviderNatTable.setSelection(new StructuredSelection(this.bodyDataProvider.getList().get(0)));
        }

        LayerListenerFixture listener = new LayerListenerFixture();
        // we register the listener to the SelectionLayer because for some cases
        // like clearing a collection, the selection change is not propagated
        // the layer stack upwards as it gets stopped on layer conversion
        selectionLayer.addLayerListener(listener);

        // Column chooser
        DisplayColumnChooserCommandHandler columnChooserCommandHandler = new DisplayColumnChooserCommandHandler(
                selectionLayer, bodyLayer.getColumnHideShowLayer(), columnHeaderLayer.getColumnHeaderLayer(),
                columnHeaderLayer.getColumnHeaderDataLayer(), null, null);
        bodyLayer.registerCommandHandler(columnChooserCommandHandler);

        this.natTable.configure();

        return this.natTable;
    }

Here is the code to registeryCheckBoxEditor & editableGridConfiguration

private void registerCheckBoxEditor(IConfigRegistry configRegistry) {

        // make checkbox cells editable
        configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE,
                DisplayMode.EDIT, COLUMN_BOOKMARK_LABEL);

        configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new CheckBoxCellEditor(),
                DisplayMode.NORMAL, COLUMN_BOOKMARK_LABEL);

        final CheckBoxPainter checkBoxCellPainter = new CheckBoxPainter();

        configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, checkBoxCellPainter,
                DisplayMode.NORMAL, COLUMN_BOOKMARK_LABEL);

        configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER,
                new DefaultBooleanDisplayConverter(), DisplayMode.NORMAL, COLUMN_BOOKMARK_LABEL);
    }

public AbstractRegistryConfiguration editableGridConfiguration(
            final ColumnOverrideLabelAccumulator columnLabelAccumulator, final IDataProvider dataProvider) {

        return new AbstractRegistryConfiguration() {

            @Override
            public void configureRegistry(IConfigRegistry configRegistry) {

                columnLabelAccumulator.registerColumnOverrides(0, COLUMN_BOOKMARK_LABEL);

                registerCheckBoxEditor(configRegistry, new CheckBoxPainter(), new CheckBoxCellEditor());

                configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE,
                        IEditableRule.ALWAYS_EDITABLE, DisplayMode.EDIT, COLUMN_BOOKMARK_LABEL);
            }

        };
    }

I have done all the settings similar to Example code but trigger mouse events are not working. Any pointer or help is really appreciated. TIA.




Toggle a attribute with id 'user'+i with a checkbox with id 'checkbox'+i

first thanks for your help in advance. I'm pretty newbie in jquery and javascript and I don't speak so much english so i cound't found nothing liked in my research.

This is my html

<li></li>
<li></li>
<li id="user1"></li>
<input type="checkbox" id="checkbox1">

<li></li>
<li></li>
<li id="user2"></li>
<input type="checkbox" id="checkbox2">

I want to everytime that a checkbox with id ("checkbox"+i) is checked I toggle a class in the ("user"+i) to push in a list and then send with post request.

I tryed this

for(i = 1; i < 3; i++) {    
   document.getElementById('checkbox' + i).addEventListener('change', function() {
        document.getElementById('user' + i).setAttribute("class", "passInterestIds");
  });
} 

but it only gives me user3 independent of the checkbox

How can I Make this work?




if checkbox is checked remove required

Here is the code
The user has to select at least one checkbox, once a checkbox is checked, I want to remove required from all the checkbox, then if the user unselect, none of the checkbox is checked, reput required on them.
My code is not working. I found lots of similar answers here but none of them works for me, so I ask this question again.




Run macro when any checkbox in worksheet is changed

I have a worksheet that runs several macros. One creates several sheets and following is another to create a checkbox for every column in each of the sheets that has been added. I have used row 80 as the linked cell for each checkbox in each worksheet.

I need to have a macro run every time any of the check boxes changes. Either on or off. I had added an extra worksheet called "info" that has a formula referring to each sheets row 80. Then I added a macro to that sheet so that every time one of the formulas changed it triggered the macro to run.

The problem I'm having now is I don't know what the sheet names are going to be. In the worksheet "info" I tried several different things like having a worksheet called "start" and then adding the worksheets between "start" and "info". I wrote the formula but then keep getting a error out of stack space.

I need someway to run a macro every time any checkbox in any worksheet changes. I don't need the "info" worksheet for anything else. I was only using it as a trigger for the macro.

'Formula in this worksheet counts the checkbox linkcell (row80)
'Each change fires this macro to create the final worksheet
Private Sub Worksheet_Calculate()
    Call CreateFinalWorksheet
End Sub




Woocommerce - Second T&C checkbox doesn't prevent checkout when left unchecked

I have a special checkbox I need placed only if the customer purchases one of two specific products. Code below looks for these product_ids, and if found, displays the additional Terms and Conditions box next to the regular T&C checkbox. While this part is working, the checkout still completes even if the box is left unchecked, so I'm guessing the problem is within the aym_not_approved_amb_terms() function, but I can't seem to figure out what that problem is.

add_action( 'woocommerce_after_checkout_form', 'aym_add_ambassador_terms_box' );
function aym_add_ambassador_terms_box() {
    // set product IDs:
    $product_ids = array( 17558, 17563 );
    $bool = false;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( in_array( $item->id, $product_ids ) )
            $bool = true;
    }
    // If product IDs detected
    if ($bool)
        // add ambassador terms checkbox
            add_action('woocommerce_review_order_after_order_total', 'aym_add_checkout_tickbox' );

            function aym_add_checkout_tickbox() {
        echo '<script>console.log("checkbox")</script>';

                echo '<p class="form-row-wide terms">';
                echo '<input type="checkbox" class="input-checkbox" name="amb-terms-check" id="amb-terms-check" />';
                echo '<label for="amb-terms-check" class="checkbox">I accept Ambassador terms and Conditions</label>';
                echo '</p>';

            }

            // Show notice if customer does not tick

            add_action('woocommerce_checkout_process', 'aym_not_approved_amb_terms');

            function aym_not_approved_amb_terms() {
                if ( ! $_POST['amb-terms-check'] )
                    wc_add_notice( __( 'Please agree to the Ambassador Terms and Conditions' ), 'error' );
            }

}

Expected behavior: if the box is left unchecked, page scrolls back up to the error message area and displays the message 'Please agree to the Ambassador Terms and Conditions'. Maybe I'm not using the correct hook for the aym_not_approved_amb_terms function...?




Android - Checkbox centering and filling layout

I have a spinner which has an item template. Inside I have a textview and a checkbox that fills the layout, but it is fixed at left border (see image). How do I make checkbox centered, while not wrapping it's content? Padding and margins don't work.

Link to checkbox image

Item template layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:local="http://ift.tt/GEGVYd"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="1">
        <TextView
            style="?android:attr/spinnerDropDownItemStyle"
            android:background="@drawable/location_item_dash"
            android:foreground="#000"
            android:ellipsize="marquee"
            android:singleLine="true"
            android:textColor="#FFFFFF"
            local:MvxBind="Text LocationName"
            android:id="@+id/spinnertext"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.8" />
        <CheckBox
            local:MvxBind="Checked Selected"
            android:background="@drawable/location_item_dash"
            android:id="@+id/spinnercheck"
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.2"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_centerInParent="true" />
    </LinearLayout>
</LinearLayout> 




ASP:Checkbox with SVG

I have to use two svg files to change the design of the checkboxes. It's have to be an asp:checkbox tag and not an input tag.

Is there a solution for my problem?

Thanks




Angularjs: checkbox and ng-change

I have problems to understand how ng-change works. I have a list of user to invite to join an auction. I want to do this with a checkbox. If the user is checked, his name has to be saved into an array. And later i will invite them(i just know how to do this). But i don't understand how to use the checkbox. I did something like this:

        <ul class="list-group" ng-repeat="user in users">
           <li class="list-group-item" ng-hide="user.name == profile">
              <img ng-src="" class="image2" >
              <div class="username"> </div>
              <div class="userrole">  </div>
              <div class="usercompany"></div>
              <input type="checkbox"  ng-model="isChecked" ng-change="insertinvited(user.name)">

           </li>
       </ul>

And in my controller:

         $scope.invited = [];
$scope.insertinvited= function (name) {

    if($scope.isChecked){
        $scope.invited.push(name)
    }
    else

    console.log($scope.invited);

};

But this is not working, in the console the array is always empty.




Answers from Radio buttons and checkboxes to mysql using php

For a survey app which has a combination of radiobuttons and checkboxes. How do I use PHP to insert the selected values to mysql db using php? This is the query for fetching the questions from db:

while($row2 = $result2->fetch_assoc())
{

if($row2["subtype"] =="radio")
{
 echo "<input id = \"radio\" class='radio_input' type=\"radio\" name=answergroup[".$row["PK_QUESTION_ID"].
"] value=".$row2["opt_id"].">".$row2["opt_text"]."</input>";

else if($row2["subtype"] =="checkbox")
{
echo "<input id = \"checkbox\" class='radio_input' type=\"checkbox\" name=answergroup[".$row["PK_QUESTION_ID"].
"] value=".$row2["opt_id"].">".$row2["opt_text"]."</input>";

}
}

I tried using $_POST['answergroup'] for fetching the selected options, but in the case of a checkbox, only one option is being fetched even if there are multiple selections made.




show and hide divs with multiple class names jquery checkboxes

I have many dives with multiple classes as

<div class="my-gallery">
  <div class="LargeFace Neutral Happy"></div>
  <div class="Sad Neutral Happy"></div>
  <div class="LargeFace Surprise Happy"></div>
  <div class="LargeFace Fear Happy"></div>
</div>

And I have multiple checkboxes which have all those values. e.g LargeFace or Happy and else.

<label class="with-label">
  <input id="c_b" type="checkbox" name="r1" value="Neutral" />Neutral
</label>
<label class="with-label">
  <input id="c_b" type="checkbox" name="r1" value="LargeFace">Large Face
</label>

Through this code I am getting all those checkbox values to an array

  $('.with-label').on "click", ->
    allVals = []
    $('.with-label :checked').each ->
      allVals.push $(this).val()
      return
    console.log allVals
    return

Right now I am really really struggling for filtering my divs on the basis of this array values. for example. User have selected multiple checkboxes and create an array as ["Happy", "Fear"]

I want to make something which will filter #my-gallery on the basis on that array. If there are 2 those values in an array then All those divs, which contain that classes should appear and other should disappear, So for other values? Is that possible? please help I am struggling with this for so long




jeudi 27 avril 2017

NatTable - CheckBoxCellEditor & CheckBoxPainter displaying the text on single click

I am using CheckBoxCellEditor and CheckBoxPainter to display Boolean attribute inside the NatTable as shown below

enter image description here

Problem : On single click of cell using mouse, it displays boolean value as text as shown below, instead of resetting the state to false.

enter image description here

Below is my code snippet,

//register the column
ColumnOverrideLabelAccumulator columnLabelAccumulator = new ColumnOverrideLabelAccumulator(
                bodyLayer.getBodyDataLayer());
        bodyLayer.getBodyDataLayer().setConfigLabelAccumulator(columnLabelAccumulator);
        columnLabelAccumulator.registerColumnOverrides(0, COLUMN_BOOKMARK_LABEL);

//added the CheckBoxCellEditor and CheckBoxCellPainter to configuration.
     natTable.addConfiguration(new AbstractRegistryConfiguration() {
                    @Override
                    public void configureRegistry(IConfigRegistry configRegistry) {
                        configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new CheckBoxCellEditor(), DisplayMode.NORMAL,
                                COLUMN_BOOKMARK_LABEL);

                        configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, new CheckBoxPainter(ImageUtil.getImage("Images.BookmarkChecked"),
                                ImageUtil.getImage("Images.BookmarkUnchecked")),
                                DisplayMode.NORMAL, COLUMN_BOOKMARK_LABEL);

                        configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER,
                                new DefaultBooleanDisplayConverter(), DisplayMode.NORMAL, COLUMN_BOOKMARK_LABEL);
                    }
                });

I also, have rowselectionProvider to set the default selection to first row and also to refresh the properties UI based on the row selection.

Any pointers on what is the missing link.TIA




Checkbox updates index mvc

Good afternoon everyone, I have an Index in my view that displays a table of restaurants (local in spanish). I added a checkbox to the view, I need the checkbox to filter the index while checked, if not then to show the complete index. I don't know if there is a way to do this with mvc,

this is my view

   @model IEnumerable<AutoPlanMCV.Models.Local>

<div class="row">
    <table class="col-md-12">
        <tr>
            <th>Nuevo</th>
            <th>Instaldo</th>
            <th>Capacitar</th>
        </tr>
        <tr>
            <td>@Model.Count(x => x.Estado.State == "Nuevo")</td>
            <td>@Model.Count(x=> x.Estado.State =="Instalado")</td>
            <td>@Model.Count(x=>x.Estado.State == "Capacitar")</td>
        </tr>
            </table>
</div>

<div class="row">
    <label for="verBajas">Ver Bajas</label>
    <input type="checkbox" name="verBajas" value="true" id="verBajas"/>

</div>

<div>   
    <p>
        @Html.ActionLink("Crear nuevo Local", "Create")
        <br />

        @Html.ActionLink("Export to Excel", "ExportToExcel")
    </p>
</div>
<div class="row">
    <div class="col-md-12">
        <div class="panel panel-primary list-panel" id="list-panel">
            <div class="panel-heading list-panel-heading">
                <h1 class="panel-title list-panel-title">POS PDS UY</h1>


            </div>
            <div class="panel-body">
                <table id="assets-data-table" class="table table-striped table-bordered" style="width:100%">
                    <thead>
                        <tr>
                            <th>V.Id</th>
                            <th>Id</th>
                            <th>Comercio</th>
                            <th>Direccion</th>
                            <th>Telefono</th>
                            <th>Ingreso</th>
                            <th>Provincia</th>
                            <th>Estado</th>
                            <th>Bonificado</th>
                            <th>Premium</th>
                            <th>Gestionar</th>

                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var asset in Model)
                        {

                            <tr>
                                <td>@asset.ViejoId</td>
                                <td>@asset.NuevoId</td>
                                <td>@asset.NombreComercio</td>
                                <td>@asset.Direccion</td>
                                <td>@asset.Telefono</td>
                                <td>@Html.DisplayFor(modelItem => asset.FechaInstalacion)</td>
                                <td>@asset.Provincia</td>
                                <td>@asset.Estado.State</td>
                                @if (asset.Bonificado == true)
                                {
                                    string i = "Bonificado";
                                    <td>@i</td>
                                }
                                else
                                {
                                    string i = "No";
                                    <td>@i</td>
                                }

                                @if (asset.Premium == true)
                                {
                                    string i = "Premium";
                                    <td>@i</td>
                                }
                                else
                                {
                                    string i = "No";
                                    <td>@i</td>
                                }

                                <td>
                                    @Html.ActionLink("Edit", "Edit", new { id = asset.Id ,estadoid = asset.Estado.Id,proveedorid = asset.Proveedor.Id}) |
                                    @Html.ActionLink("Details", "Details", new { id = asset.Id }) |
                                    @Html.ActionLink("Delete", "Delete", new { id = asset.Id })|
                                    @Html.ActionLink("Comment", "AgregarComentario", new { id = asset.Id })
                                </td>
                                                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@section Scripts
{

    <script type="text/javascript">
     $(document).ready(function () {

         $('#assets-data-table').DataTable();
     });
    </script>

}

this is the actionResult in my controller

public ActionResult IndexAsset(bool verBajas = false)
    {


       var locales = db.Locales.Include(l => l.Estado).Include(l => l.Proveedor).Where(l => l.Proveedor.Nombre == "PDSUY");

        if(verBajas)
        {
            locales = db.Locales.Include(l => l.Estado).Include(l => l.Proveedor).Where(l => l.Proveedor.Nombre == "PDSUY").Where(l => l.Estado.State != "Bajas");
        } else if (verBajas == false)
        {
            locales = db.Locales.Include(l => l.Estado).Include(l => l.Proveedor).Where(l => l.Proveedor.Nombre == "PDSUY");
        }



        return View(locales.ToList());
    }

If I dont initialize "verBajas" as false, I get a null error, even though I set the value in the view as true.

Any Ideas are appreciated.




jQuery add multiple filter parameters to url

I have multiple groups of checkboxes that are used to filter search results. For example, a search for shirts would have group one as colors, which includes things like, black, blue, red and group two as sizes, which includes things like, small, medium, large. Standard stuff...

The url for this example would look like the following, after a search is made, and the filters are applied:

http://ift.tt/2pnmUUs

This would return me all items that match the keyword search, with the filters of colors (red and black), and sizes (small and medium).

I have all of the backend done, but I am not very great when it comes to the front end of things...

The code below does just about what I want, except it has it's flaws for my situation which I've explained below.

<script type="text/javascript">
      function GetFilters() {
          console.log("rom");
          $('input[type="checkbox"]').on('change', function (e) {
              var data = {},
                  fdata = [],
                  loc = $('<a>', { href: window.location })[0];
              $('input[type="checkbox"]').each(function (i) {
                  if (this.checked) {
                      if (!data.hasOwnProperty(this.name)) {
                          data[this.name] = [];
                      }
                      data[this.name].push(this.value);
                  }
              });
              // get the key
              var key = Object.keys(data)[0];
              // and the data
              // it works to without joining
              var fdata = key+"="+data[key].join(',');
              // and if you wanna strip the whitespaces
              // use fdata = fdata.replace(/\s/g,"");
              $.ajax({
                type: "POST",
                url: "/ajax/get",
                data: {
                      "_token": "",
                      "fdata": fdata
                    },
                success: function (response) {
                  $('#d2d-results').html(response);
                }
              });
              if (history.pushState) {
                  history.pushState(null, null, loc.pathname + '?' + fdata);
              }
          });
      }
      window.onload = GetFilters;
  </script>

The code works for the most part. When I click a checkbox, it appends to the url and the ajax request is done. Works great...

But the issues I am having with said code is that when I uncheck the last checkbox to remove the final filter, it stays in the url, and casts an error:

Uncaught TypeError: Cannot read property 'join' of undefined
    at HTMLInputElement.<anonymous> (677)
    at HTMLInputElement.dispatch (jquery.min.js:3)
    at HTMLInputElement.q.handle (jquery.min.js:3)

Second, the code only works when I use one filter group. If I try to click a checkbox from another filter group while a selection is already made from the first, for instance if colors=red,black are already selected, things fail, and for obvious reasons, because the code doesn't seem to allow it.

How can this be modified to add multiple query groups? How can I click red and black from my colors group and small and medium from my sizes group and have the url display:

http://ift.tt/2pnmUUs

But also remove the actual query if I don't want to specify colors for instance?

http://ift.tt/2pEjcc6




Angular JS TypeScript Primeng DataTable - Multi select, row grouping : Set checkboxes for rows at runtime

I am using PrimeNG Ultima theme in my Angular JS application. I have datatable like below with multiple selection and row grouping.

<p-dataTable #restrictionDT 
      [value]="apprestrictions" 
      selectionMode="multiple" 
      [(selection)]="selectedApprestrictions" 
      sortField="belongsTo" 
      rowGroupMode="subheader" 
      groupField="belongsTo" 
      expandableRowGroups="false" 
      [responsive]="true">
          <ng-template pTemplate="rowgroupheader" let-rowData>
                      
          </ng-template>
       <p-column selectionMode="multiple"></p-column>
       <p-column field="id" header="ID"></p-column>
       <p-column field="name" header="Name"></p-column>
       <p-column field="displayBelongsTo" header="Belongs To"></p-column>
</p-dataTable>

I can see my datatable like below. I am able to select individual row, can select multiple rows, I can also select all rows if I check checkbox on that top.

Data Table

We have a requirement to group rows and I am able to do that also. Our requirement is that in row group header we need to add checkbox so that if user checks that checkbox only the rows belonging to that row group must be checked. For example in my datatable I will add check box beside A1. If that is checked then two rows with ID 1 and 5 must be selected but not others.

I already approached PrimeNG team and they say as of now p-datatable will not support what we want. So I am trying to see what I can do. From debug I noticed that each row has p-dtcheckbox and ng-reflect-checked will be true when it is checked and false when it is not. So I am trying to set that in my typescript code. Can anybody tell me how to do this. enter image description here

Please see my code below

import { Component, OnInit, ViewChild, OnDestroy, ElementRef } from '@angular/core';

@ViewChild('restrictionDT') restrictionDT: ElementRef;

console.log(this.restrictionDT);

console.log(this.restrictionDT) works good and I can see data table in my browser console. But this.restrictionDT.nativeElement is undefined so there I am stuck




Why can I not change the 'checked' status of a checkbox in Javascript?

Intended behaviour

I have a checkbox inside of a div element. I want both the box and the div to be clickable.

  • When the checkbox is clicked by the user, a class is added to the div to change its background colour. This class is then removed if the checkbox is clicked again.
  • When the div itself is clicked, the class with the background colour is added or removed as appropriate and the checkbox is ticked or unticked too

Currently, I have most of this working using plain javascript:

function boxPress(markNumber) {
  var checkbox = "mark" + markNumber;
  var element = document.getElementById(checkbox);
  var markbox = "markbox" + markNumber;
  if (element.getAttribute("checked") == null) {
    element.setAttribute("checked", "true");
    document.getElementById(markbox).classList.add('checked');
  } else {
    element.removeAttribute("checked");
    document.getElementById(markbox).classList.remove('checked');
  }
}
.mark {
  margin-bottom: 5px;
  margin-top: 5px;
  background-color: #FFFFFF;
  border-width: 2px;
  border-radius: 0px 5px 5px 0px;
  border-left-style: solid;
  border-left-width: 10px;
  border-color: lime;
  overflow: auto;
  padding: 2%;
  transition: background-color 0.5s linear 0s;
  cursor: pointer;
}

.checked {
  background-color: #66ff66;
}

.mark:hover {
  background-color: #fffcaf;
}

.checked:hover {
  background-color: #b3ffb3;
}

.flex-container {
  display: -webkit-flex;
  display: flex;
  align-items: center;
  margin: 0px;
  padding: 0px;
}

.flex-mark {
  width: 85%;
  margin: 0px;
}

.flex-tick {
  width: 15%;
  margin: 0px;
  text-align: center;
}

.flex-tick input {
  width: 40px;
  height: 40px;
}
<div class="mark col-12 col-m-6" id="markbox0" onclick="boxPress(0)">
  <div class="flex-container">
    <div class="flex-mark">
      <p>Candidate introduces themself by first name, surname and role</p>
    </div>
    <div class="flex-tick"><input type="checkbox" id="mark0"></div>
  </div>
</div>

This works perfectly, apart from where the user first interacts with the checkbox, then later with the div element.

Steps to reproduce the problem in the above snippet:

  1. Click the div. The background changes and the checkbox is ticked.
  2. Click the div again. The changes are reversed as expected.
  3. Click the checkbox. The background change is applied.
  4. Click the checkbox again. The change is reversed as expected.
  5. Now click the div again. The background changes happen but the checkbox remains unticked

Even more interestingly, the HTML of the checkbox reads:

<input type="checkbox" id="mark0" checked="true">

Yet the browser doesn't render the box as checked.

Why is this happening, and why is it only a problem when the div click comes after the box click? It happens in both Chrome and Edge.




Design SQL Server database correctly

I have simple registration form, but there are 3 checkboxes for example:

Name:   [        ]
Email:  [        ]
Pass:   [        ]
What do you like at free time?  
  Reading:    [ ]
  Travelling: [ ]
  Sport:      [ ]

As in example above you see "What do you like at free time?" There are 3 checkboxes. There are multiple options, people could check only Reading checkbox or Reading and Travelling or all checkboxes, etc.

How to store it correctly in the database?

For example If I'll create Users table in following:

CREATE TABLE #User
(
    Id INT IDENTITY,
    Name NVARCHAR(60),
    Email NVARCHAR(60),
    Password NVARCHAR(60),
    FreeTime INT
)

I could insert only 1 choice from checkbox. Comma separated solution is bad practice.

I don't know If It's good practice in users table insert multiple records with the same UserId to insert all checkboxes values as separate rows?

Or better way to create new table FreeTime something like?

CREATE TABLE #FreeTime
(
    Id INT IDENTITY,
    UserId INT,
    Description NVARCHAR(60)
)




show and hide div on multiple checkbox values jquery

I have div like that

<div data-tags=" LargeFaceDetected Neutral"></div>
<div data-tags=" LargeFaceDetected Sadness"></div>
<div data-tags=" LargeFaceDetected Sadness Neutral"></div>
<div data-tags=" LargeFaceDetected Happy"></div>

And I have filtered them on the basis of check box values, my each checkbox look like this

            <a href="#">
              <label class="with-label">
                <input type="checkbox" name="r1" value="LargeFaceDetected">Large Face
              </label>
            </a>

and In jquery side what I am doing is

filterImages = (e) ->
  regex = new RegExp('\\b\\w*' + e + '\\w*\\b')
  $('.for-filter').hide().filter(->
    regex.test $(this).data('tags')
  ).show()
  return

onImageSearch = ->
  $('.with-label').on "click", ->
    console.log $('input[name=r1]:checked').val()
    selectTag = $('input[name=r1]:checked').val()
    filterImages(selectTag)
    return

But this only works for one values at a time. As In past I was working with Radio buttons instead of checkboxes. But Now I have all checkboxes, and Its not working if there is multiple checkboxes have been selected. For example: User have selected LargeFaceDetected And Neutral, then all divs containing those values should appear, But Now only appearing which have been clicked first. Please help me in this.




how to access object value in angular js

I want to access object value(i.e rulenames-decline,postpone,warning...) in checkbox, using ng-repeat and also display checkbox as checked when value in object is 'Y' and unchecked when value is 'N'

<div class="form-group">
<label class="checkbox-inline" ng-repeat="rules in savedRulesData ">
<input type="checkbox" id="checkBoxed" value="">
</label>
</div>

Currently my checkbox is displayed as illustrated in image.

I open this model using editRules Function in my controller

[http://ift.tt/2qbfV3R] Image link

$scope.editRules = function(ruleTypes,client) {
        var obj=new Object();
        var self=this;
        var clientId=client.clientId;

        var responsePromise = $http.get("typesofSavedRules/"+clientId);
        responsePromise.success(function(data, status, headers, config) {
            self.savedRulesData=data.objList;   
            $scope.savedRulesData=self.savedRulesData;
        });
        responsePromise.error(function(data, status, headers, config) {
            alert("AJAX failed!");
        });

        modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            scope: $scope,
            size:'lg'
        });
    };




Checkbox tick issue in IE browser

custom checkbox tick not working in ie and firefox browser, its shows default tick,how to change default tick into custom tick in ie browser. Please give me some idea!!

Chrome browser checkbox IE browser checkbox

Below the following code of checkbox

input[type="checkbox"] {
    -webkit-appearance: none;
    -moz-appearance: none;
    -ms-appearance: none;
    appearance: none;
    height: 17px;
    width: 17px;
    cursor: pointer;
    position: relative;
    -webkit-transition: .15s;
    border-radius: 5px 5px 5px 0;
    border: 1px solid #d7d7d7;
    vertical-align: middle;
    background-color: #fff;
}

    input[type="checkbox"]:before, input[type="checkbox"]:checked:before {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        line-height: 1.2em;
        text-align: center;
        color: #656464;
        content: '';


    }

    input[type="checkbox"]:checked:before {
        content: '✔';


    }

/*checkbox code for IE browser*/
::-ms-check {
        cursor: pointer;
        position: relative;
        -webkit-transition: .15s;
        -moz-transition: .15s;
        -ms-transition: .15s;
        border-radius: 5px 5px 5px 0;
        border: 1px solid #d7d7d7;
        vertical-align: middle;
        background-color: #fff;
        color:#656464;

    }


    ::-ms-check:before, ::-ms-check:checked:before {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        line-height: 1.2em;
        text-align: center;
        color: #656464;
        content: '';
    }

    ::-ms-check:before {
        content: '✔';
    }




JQuery: Checkbox Chain not working properly

I have 'chain' of checkboxes (parent checkbox and childs), and problem is:

When first clicking on 'parent' checkbox it is working well, but after that when clicking on 'childs', the 'parent' checkbox then isn't doing what is supposed. Parent is checking/unchecking childs except the child which was pressed before.

Here is code:

JavaScript

checks_bind();
function checks_bind(){
  $("#x_main").off('click');
  $("#x_main").on('click',function(){
  var obj   = $(this);
    var val = obj.is(':checked');
    $("#checks").find("input[type='checkbox']").attr('checked',val);
  });
}

HTML

<input id='x_main' type='checkbox'/>Main<br>
<p>--------------------------------</p>
<div id='checks'>
<input type='checkbox'/>1<br>
<input type='checkbox'/>2<br>
</div>
<p>--------------------------------</p>
<i>1 - Click on 1 or 2 <br>2 - Try <b>Main</b> checkbox. <br>
3 - Main checkbox isn't working</i>

jsfiddle example

And one more question:

Is it good to use .on('click.namespace') on checkboxes since it's working well? I can use .change() method, but I want to call .off('click.namespace') (or something to unbind) before .on() each time when calling the function.




Java Checkbox Save

i Need some help with saving checkboxes, im new in this and hope i'll get some help.

What i want to do: I want to save the Settings:

if(e.getSource() == einstellung){


        JFrame meinJFrame = new JFrame();
        meinJFrame.setTitle("JRadioButton Beispiel");
        meinJFrame.setSize(400,300);
        JPanel panel = new JPanel();
        panel.setBackground(Color.BLACK);
 //Checkbox 1

        JCheckBox check = new JCheckBox("Activate Wall at the score of 500k.", false);

        panel.add(check);

      //Checkbox 2
        JCheckBox check1 = new JCheckBox ("Activate Trump Tower at the score of 1 million.", false);

        panel.add(check1);           

        meinJFrame.add(panel);
        meinJFrame.setVisible(true);

It's for a little game i am creating and i just want to save the checkboxes, so they are checked (or not) when i start the Programm again.

The full code (please do not use it for private things like using it for your own game or sth like that):

private JButton schliessen;
private JButton einstellung;
private JButton info;
private JButton ende;
private JTextField Textbox;

JCheckBox redCB, blueCB, greenCB, yellowCB;


public static void main(String[] args) throws Exception {






    frame frame = new frame("Jump Trump Menu");
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400,460);
    frame.getContentPane().setBackground(Color.BLACK);  


    frame.setLayout(null);
    frame.setVisible(true);














}








public frame(String title) {

    super(title);

    schliessen = new JButton("Play");
    schliessen.setBounds(120,40,160,40);
    schliessen.addActionListener(this);
    add(schliessen);
    schliessen.setBorderPainted(false);
    schliessen.setFocusPainted(false);
    schliessen.setContentAreaFilled(true);
    schliessen.setHorizontalAlignment(JButton.CENTER);

    einstellung = new JButton("Settings");
    einstellung.setBounds(120,120,160,40);
    einstellung.addActionListener(this);
    add(einstellung);
    einstellung.setBorderPainted(false);
    einstellung.setFocusPainted(false);
    einstellung.setContentAreaFilled(true);
    einstellung.setHorizontalAlignment(JButton.CENTER);

    info = new JButton("Special Contract");
    info.setBounds(120,200,160,40);
    info.addActionListener(this);
    add(info);
    info.setBorderPainted(false);
    info.setFocusPainted(false);
    info.setContentAreaFilled(true);
    info.setHorizontalAlignment(JButton.CENTER);

    ende = new JButton("Exit");
    ende.setBounds(120,280,160,40);
    ende.addActionListener(this);
    add(ende);
    ende.setBorderPainted(false);
    ende.setFocusPainted(false);
    ende.setContentAreaFilled(true);
    ende.setHorizontalAlignment(JButton.CENTER); 

    Textbox = new JTextField("Pre Alpha 0.0.5");
    Textbox.setHorizontalAlignment(JTextField.CENTER); 
    Textbox.setBounds(120,360,160,40);
    add(Textbox);
    Textbox.setEditable (false);


}



public static void fenster(){


    JFrame fenster = new JFrame("JumpTrump");
    fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    fenster.setSize(650,350);
    fenster.setVisible(true);
    fenster.add(new gui());
    fenster.setResizable(false);







    }

//public static void auswahl(){

//}



@Override
public void actionPerformed(ActionEvent e) {

    // TODO Auto-generated method stub

    if (e.getSource()== schliessen ){
        fenster();


            URL url = SoundTest.class.getResource("donald.au");
            AudioClip clip = Applet.newAudioClip(url);

            clip.play();

            clip.loop();

    }

    if (e.getSource() == info ){
        Object[] options = { "Agree", "Disagree", "Die Now"};


        if (e.getSource()== options){
            System.exit(0);
        }
    int result =    JOptionPane.showOptionDialog(null,"Programmed by Zensoran your lord and king  ! By clicking (Agree) you swear that you give your life to the holy King of Steam (Lord Gaben), by clicking (Disagree) you won't get a Steam Summer sale!","Contract",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE,null,options,options[2]);    

        if (result == JOptionPane.YES_OPTION);
        if (result == JOptionPane.NO_OPTION) System.exit(0);
        if (result == JOptionPane.CANCEL_OPTION) System.exit(0);

    }


    if(e.getSource() == einstellung){


        JFrame meinJFrame = new JFrame();
        meinJFrame.setTitle("JRadioButton Beispiel");
        meinJFrame.setSize(400,300);
        JPanel panel = new JPanel();
        panel.setBackground(Color.BLACK);
 //Checkbox 1

        JCheckBox check = new JCheckBox("Activate Wall at the score of 500k.", false);

        panel.add(check);

      //Checkbox 2
        JCheckBox check1 = new JCheckBox ("Activate Trump Tower at the score of 1 million.", false);

        panel.add(check1);           

        meinJFrame.add(panel);
        meinJFrame.setVisible(true);















    }

    if(e.getSource() == ende){

        if (JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?", "WARNING",
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
            System.exit(ERROR);
        } else {


              }
            }











}

}




at least one checkbox must stay selected on deselect action of one of them

I have a few checkboxes on a form and i want to validate them when deselecting every one of them. So at least one checkbox must stay selected on deselect event.

function validateCBox() {
var checkBoxes = document.getElementsByClassName('myCBox');
var isChecked = false;
    for (var i = 0; i < checkBoxes.length; i++) {
        if ( checkBoxes[i].checked ) {
            isChecked = true;
        };
    };
    if ( isChecked ) {
        alert( 'checked!' );
        } else {
            alert( 'please check at least one checkbox!' );
        }   
}
<form>
  <input type = "checkbox" class='myCBox' value = "a">1
  <input type = "checkbox" class='myCBox' value = "b">2 
  <input type = "checkbox" class='myCBox' value = "c">3
  <input type = "checkbox" class='myCBox' value = "d">4
</form>
<input type = "button" value = "Edit and Report" onClick="validateCBox()">



jquery checkbox is not working on single click

I am not sure what i am doing wrong but i have to changge a checkbox state on click of an image and its not working

I have a checkbox in a repeater controls whose attribute data-id-chk gets set from page behined

<asp:CheckBox ID="chk_QuizQuestionOptionGUID" runat="server" CssClass="QuestionFormRadioButton" data-id-chk="0" />

then there is a aspx wheere i am simplay calling the javascript function on click of an image. but i want to change checkbox state which is not getting changed.

function AddRemoveStyle(target) {
    try {

    var dataid = $(target).attr("data-id-img");

    var mychk = $('[data-id-chk="'+ dataid +'"]');

    var ckb = $(mychk[0]).is(':checked');
    if (!$(mychk[0]).is(':checked')) {
        $(mychk[0]).prop('checked', true);
    }
    else{           
        $(mychk[0]).prop('checked', false);
    }


    }
    catch (e) {
        // statements to handle any exceptions
        alert(e); // pass exception object to error handler
    }
}

</script>

here is the image to call the above method:

<a href="#" id="Photo4">
<div>
<div>
<asp:Label ID="lbl_QuizQuestionOptionGUID" runat="server" Visible="false" Text='<%#Eval("QuizQuestionOptionGUID")%>'></asp:Label>
<img id="img_Option" runat="server" src="/assets/images/null.gif" alt="null" onclick="AddRemoveStyle(this);" />                                                                                                 
</div>
</div>




Checked="Checked" not working after target Checkbox was clicked once

I have the following GridView:

<asp:GridView ID="gvSpecificRights" runat="server" AutoGenerateColumns="false" OnRowCreated="gvSpecificRights_RowCreated" CssClass="mGrid" ShowHeaderWhenEmpty="true" ShowFooter="true">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate><asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>'></asp:Label></ItemTemplate>
            <FooterTemplate><asp:DropDownList ID="ddlAvailableUsers" runat="server"></asp:DropDownList></FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Create" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
            <ItemTemplate><asp:CheckBox ID="cbTickCreator" runat="server" Checked='<%# Eval("TickCreator") %>' CssClass="clicknext"></asp:CheckBox></ItemTemplate>
            <FooterTemplate><asp:CheckBox ID="cbFooterTickCreator" runat="server" CssClass="clicknext"></asp:CheckBox></FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Read" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
            <ItemTemplate><asp:CheckBox ID="cbTickViewer" runat="server" Checked='<%# Eval("TickViewer") %>'></asp:CheckBox></ItemTemplate>
            <FooterTemplate><asp:CheckBox ID="cbFooterTickViewer" runat="server"></asp:CheckBox></FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="btnSave" runat="server" Text="<i class='fa fa-floppy-o'></i>" OnClick="btnSave_Click" CommandArgument='<%# Eval("ID")%>'/>
            </ItemTemplate>
            <FooterTemplate>
                <asp:LinkButton ID="btnAdd" runat="server" Text="<i class='fa fa-plus'></i> Hinzufügen" OnClick="btnAdd_Click" />
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

My goal is to automatically check and disable the Read-Checkbox, when the Create-Checkbox is clicked. Therefore I was able to create the following script:

<script>
    document.getElementById('Form').addEventListener('click', function (e) {
        if (e.target.parentElement.getAttribute("class") === 'clicknext') {
            if (jQuery(e.target).is(":checked")) {
                e.target.parentElement.parentElement.nextElementSibling.firstChild.setAttribute("checked", "checked");
                e.target.parentElement.parentElement.nextElementSibling.firstChild.setAttribute("disabled", "disabled");
            }
            else {
                e.target.parentElement.parentElement.nextElementSibling.firstChild.removeAttribute("checked");
                e.target.parentElement.parentElement.nextElementSibling.firstChild.removeAttribute("disabled");
            }
        }
    });
</script>

You may wonder why I was using .parentElement twice. This is because ASP.net will wrap a span around the checkbox, if you apply a css-class on it.

So the script works like a charm if i open the containing page and click the "Create"-Checkbox: The "Read"-Checkbox gets checked too and will be disabled. Unchecking the "Create"-Checkbox also works fine: The "Read"-Checkbox gets unchecked and reenabled.

BUT: As soon as I've checked or unchecked the "Read"-Checkbox manually once, the script won't work anymore. It's still able to enable/disable the "Read"-Checkbox and also sets the checked-attribute (seen over development-console), but the browsers (Firefox, Chrome) will not render it as checked.

Do you have any idea, what I'm doing wrong here? Thanks in advance!