I have created activity_main.xml with listview , checkbox , textview and button. i want that to bind the checkbox and text and get the id of checked items in onclick to move the items when button is clicked and show the items in listview2...
lundi 30 novembre 2015
ModelState validation fails when the CheckBox is unchecked
In the view:
@Html.CheckBoxFor(m => m.Insert_DSA.ChkFlag)<b>Check this if you want to change the password at your first login</b>
there's no validation of any sort for this checkbox done manually by me,but still when the correctly validated data is posted to the controller ModelState.IsValid
property isfalse
if the checkbox is unchecked. When i looked for the ModelState errors using
var errors = ModelState.Where(x => x.Value.Errors.Any()).Select(x => new { x.Key, x.Value.Errors });
it gives me
The ChkFlag field is required.
What I want: I don't want the checkbox to be a required field and I want ModelState.IsValid
property to be true even when the checkbox is unchecked.
How can bind nullable boolean field in razor mvc5?
I pass model to my razor. One of field is bool? . How can i bind this field to check box ?
@model bool?
@Html.CheckBox(...)
@Html.CheckBoxFor(...)
@Html.CheckBox("", Model.GetValueOrDefault())
ionic local storage and checkbox
I have created a checkbox in a modal: but when ever I close and reopen the modal, the items that were checked are not shown as checked. here are my codes
<div class="list">
<ion-checkbox ng-repeat="thema in themen track by $index"
type="checkbox"
id="{{thema.id}}"
ng-model="thema.checked"
ng-checked="thema.checked">
{{ thema.name }}
</ion-checkbox>
</div>
and in the js file I have added
$scope.openModal = function() {
$scope.modal.show();
$scope.themen = [
{ name: 'something', id: 1 },
//some other objects
];
};
$scope.closeModal = function() {
$scope.updateThemaLocalStorage = function ($index) {
$window.localStorage.setItem( $index, $scope.themen[$index].checked );
};
$scope.modal.hide();
};
also in gulp watch
I recive error "$index" is defined but never used no-unused-vars
How to replace default html checkbox with just html+css and no images?
I would like to visually replace the default checkbox element with a styled div that appears on top of the checkbox. I don't want to use an image.
When checked:
<div style="width: 18px; height: 18px; background: #0e0; border-radius: 3px; border: 2px solid #555; color: #fff;">✓</div>
When unchecked:
<div style="width: 18px; height: 18px; background: #ccc; border-radius: 3px; border: 2px solid #555; color: #fff;"></div>
Can it be done?
Thanks!
Keeping track on Checkbox count in JavaScript
I want to keep track of my checkbox count. i.e, for example if i have 3 checkboxes Apples Mangoes Oranges when i check on Apples check box, it should show the count as 1 next to the label, if i click oranges check box it should show it should show the count as 2. Now, if I uncheck Apples, now oranges count should become 1 and apples should become 0.
I have tried the following code :
<input type="checkbox" name="apples" id="fruits"/> Apples <br/>
<input type="checkbox" name="mangoes" id="fruits"/> Mangoes <br/>
<input type="checkbox" name="oranges" id="fruits"/> Oranges <br/>
<script>
var inputElems = document.getElementByTagname("input");
for (var i=0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox" && inputElems[i].checked === true)
{
if(inputElems[i].id === "apple")
{
count1++;
count1 = count1+count2+count3;
alert('count for apples: '+count1);
}
if(inputElems[i].id === "mango")
{
count2++;
count2 = count1+count2+count3;
alert('count for mangoes: '+count2);
}
if(inputElems[i].id === "orange")
{
count3++;
count3 = count1+count2+count3;
alert('count for oranges: '+count3);
}
}
}
}
Here, I have tried putting values in alert boxes. But I want to try putting it next to the label. i.e: Apples (1) Mangoes (3) Oranges (2) like this according to the checkbox I select. How do I do that? Please help me.
Thanks, Shruthi
Parent node checked but child node is not checked when want to retrieve saved data from database TreeView checkbox
I have did the checkbox treeview. It is successfully save to my database as well. But it just did not checked it back the checkbox. It only checked the parent node, but the child node is still remaining unchecked.
Here is the javascript for the checkbox.
<script type="text/javascript">
$(function () {
$("[id*=tvPermission] input[type=checkbox]").bind("click", function () {
var table = $(this).closest("table");
if (table.next().length > 0 && table.next()[0].tagName == "DIV") {
//Is Parent CheckBox
var childDiv = table.next();
var isChecked = $(this).is(":checked");
$("input[type=checkbox]", childDiv).each(function () {
if (isChecked) {
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
} else {
//Is Child CheckBox
var parentDIV = $(this).closest("DIV");
if ($("input[type=checkbox]", parentDIV).length == $("input[type=checkbox]:checked", parentDIV).length) {
$("input[type=checkbox]", parentDIV.prev()).prop("checked", true);
} else {
$("input[type=checkbox]", parentDIV.prev()).prop("checked", false);
}
}
});
})
behind code to save:
foreach (TreeNode tn in tvPermission.CheckedNodes)
{
Page p = new Page();
p.Name = tn.Text;
p.Url = tn.Value;
validation.AddRange(PageManager.Save(p));
}
this is the behind code to display it back:
foreach (TreeNode tn in tvPermission.Nodes)
tn.Checked = (role.AccessPages.Where(p => p.Url == tn.Value).ToList().Count() > 0);
Unchecking box in jquery [on hold]
So I wrote a function that shows and hide images when you click on a certain checkbox. The checkboxes are stars and they represent hotel star ratings. When you check a different box the previous box is still checked, and when you uncheck it the image for that checkbox appears.
How can I prevent images from showing when you unclick a checkbox?
I put the star rating checkbox under <!-- Star Ratings -->
and the hotels under <!-- Hotel Body -->
How to add a label on the checkbox simple_form and style the label inline to the checkbox?
I have a checkbox which doesn't have a label. How do I add a label tag in simple_form where the checkbox is inserted in the HTML label tag.
I currently have checkbox and plain text after it.
<%= f.check_box :is_positive, as: :boolean, checked_value: true, unchecked_value: false %> Is positive?
I tried the below code, but it makes the label higher than the actual checkbox.
<%= f.input :is_positive, as: :boolean, checked_value: true, unchecked_value: false, inline_label: 'Is positive?' %>
Is there a way to label the checkbox and have its label inline to the checkbox?
Javascript, Determining Which Checkboxes Are Checked
I'm writing up product comparison functionality and it's going rather well, however, I'm having some trouble looping and checking the states of the checkboxes which will determine which products to compare. For example, I may click the compare checkbox on 3 items and then click 'compare selected' and the intention is that all 3 products that are checked will be displayed in a comparison window.
Now, the checkboxes in question are appended dynamically to the page via WordPress and are given a class of 'comparable--object' and a unique identifier using a data attribute.
Here's my HTML
<label>Checkbox</label>
<input class="comparable--object" data="0" type="checkbox">
<label>Checkbox</label>
<input class="comparable--object" data="1" type="checkbox">
<label>Checkbox</label>
<input class="comparable--object" data="2" type="checkbox">
<label>Checkbox</label>
<input class="comparable--object" data="3" type="checkbox">
I'm using this to loop through all the checkboxes on the page.
var checkboxes = document.querySelectorAll('.comparable--object');
for(var obj = 0; obj < checkboxes.length; obj++) {
self = checkboxes[obj];
// determine which checkboxes are checked
}
I tried to effectively assign an event listener to each self object in the loop, however, this would only return the last index for each checkbox i.e. self[maxlength];
I tried using .checked and still nothing... I feel i'm over complicating this...
Thanks for any feedback!
Checkboxes align to the right on Chrome in Windows, not in Mac
I have a form in my Rails app with a stack of checkboxes. Rails generates these dynamically in the view based on the column_names
of one of my tables.
On my Mac in Chrome the checkboxes render perfectly, with the checkbox on the left and text to the right. In Windows however, still in Chrome, the checkboxes render far to the right and cover the text.
How do I fix the checkbox placement on Windows?
Chrome On Mac
Chrome On Windows
View
<% @conditions.each do |x| %>
<div class="checkbox">
<label>
<%= i.check_box "#{x}".to_sym, {} %>
<%= x.humanize.split.map(&:capitalize).join(' ') %>
</label>
</div>
<% end %>
Inspector in Chrome on Windows
DataGridView in Check box column counting increment and discriminant in VB.net ? Help me
Look Like This type code but something wrong .. :(
Friend Function Re_chk(ByRef Dgv1 As DataGridView) As Boolean Re_chk = False Try Dim count1 As Integer = 1 For Each row As DataGridViewRow In Dgv1.Rows If row.Cells(7).Value = True Then count1 += 1 End If Next For Each row As DataGridViewRow In Dgv1.Rows If row.Cells(7).Value = False Then count1 -= 1 End If Next Student_Details.LblAttendceCont.Text = count1 Re_chk = True Catch ex As Exception MsgBox(ex.Message) End Try End Function
Pass checkbox value IF the checkbox is checked
I have a list of checkboxes that looks like this:
<div class="checkbox">
<label><input type="checkbox" value="west" name="west" id="west" checked="{{isChecked}}">West</label>
</div>
<div class="checkbox">
<label><input type="checkbox" checked="{{isChecked}}" name="airport" id="airport" value="airport">Airport</label>
</div>
<div class="checkbox">
<label><input type="checkbox" checked="{{isChecked}}" name="north" id="north" value="north">North</label>
</div>
I have managed to pass the status of each checkbox as a boolean to the collection like this:
var eventLocation = [
event.target.west.checked,
event.target.airport.checked,
]
However, I would like to pass only the value of the checked checkboxes. I know I can pass the value of the checkboxes with event.target.west.value
, but to get only the checked ones I would have to write many conditionals, which would not scale well. Is there a better way of doing this?
Thank you!
How To Uncheck Default Checkbox When Another Is Checked - Angular
I need to have the first value "none" checked as default and then unchecked when any of the other options are checked. I have found the way to do this using the ng-model but I'm using ng-model to build an object for email. Is there a way that I can do this using an angularish style?
<div class="activate-mail-subsection">
<label>Allergies</label><br>
<div class="checkbox mailorder-checkbox">
<input name="allergies" class="checkbox" type="checkbox" ng-model="mailorder.allergies.none" tabindex="1"/> None
</div>
<div class="checkbox mailorder-checkbox">
<input name="allergies" class="checkbox" type="checkbox" ng-model="mailorder.allergies.codeine" tabindex="1"/> Codeine
</div>
<div class="checkbox mailorder-checkbox">
<input name="allergies" class="checkbox" type="checkbox" ng-model="mailorder.allergies.sulfa" tabindex="1"/> Sulfa
</div>
<div class="checkbox mailorder-checkbox">
<input name="allergies" class="checkbox" type="checkbox" ng-model="mailorder.allergies.asprin" tabindex="1"/> Asprin
</div>
<div class="checkbox mailorder-checkbox">
<input name="allergies" class="checkbox" type="checkbox" ng-model="mailorder.allergies.penicillin" tabindex="1"/> Penicillin
</div>
<div class="checkbox mailorder-checkbox">
<label>Other</label>
<input name="allergies" class="form-control health-profile-text" type="text" ng-model="mailorder.allergies.other" tabindex="1"/>
</div>
</div>
Here is the object
$scope.mailorder = {
allergies: {none: true, codeine: false, sulfa: false, aspirin: false, penicillin: false, other: ''},
};
How to insert multiple checkbox data jsp into database using three-tier archi
I want to insert multiple data into the database using checkbox, but I dont know how to insert it using three-tier. I tried to use an array to store it into the database, but it failed.
Below is snippet of my code addTask.jsp
<form action="addTaskAction.jsp">
<h1>New Task</h1>
<table border="0">
<tr><td>
<p><label for="taskDesc">Task Description</label>
</td><td>
<textarea rows="4" cols="41" name="taskDesc" ></textarea></p>
</td></tr>
<tr><td>
<p><label for="groupId">Labour Groups</label>
</td><td>
<input type="checkbox" name="lgroup" value="driver">Driver Group
<br>
<input type="checkbox" name="lgroup" value="patching">Road Patching Group
<br>
<input type="checkbox" name="lgroup" value="rshoulder">Road Shoulder Group
<br></p>
</td></tr>
</table>
<p><input type="submit" value="Submit"></p>
</form>
then, below is addTaskAction.jsp
<%
String taskDesc = request.getParameter("taskDesc");
String groupId = "";
String arr[] = request.getParameterValues("lgroup");
for(int i=0; i<arr.length; i++){
groupId += arr[i]+" ";
}
String a = task.addTask(taskId, taskDesc, taskDate, taskDuration, groupId, roadId);
if((a.equals("success"))){
%><script>alert("Task Successfully Added ");</script>
<script>window.location="viewTask.jsp";</script><%
}
else{%>
<script>alert("Adding Task Failed ");</script>
<script>window.location="addTask.jsp";</script><%
}
%>
Then, this is task.java (Controller)
public static String addTask(String taskDesc, String groupId){
String a = taskDA.addTask(taskDesc, groupId);
return a;
}
Then this is taskDA.java (Data Access Layer)
public static String addTask(String taskDesc, String groupId){
Connection myConn;
Statement myStmt;
try {
myConn = connectionManager.getConnection();
myStmt = myConn.createStatement();
ResultSet result = myStmt.executeQuery("insert into TASK (TASKDESC, G_ID) values ('" + taskDesc + "','" + groupId + "') ");
return "success";
} catch (Exception sqlEx) {
System.err.println(sqlEx);
return "a:" + sqlEx;
}
}
I really hope that anyone can help me with this problem, pleaseee. It really means a lot
A 'check all' checkbox (JavaScript) in a PHP 'while loop'
I'm looking for a way to use JavaScript in the following piece of code. I want the checkbox with id = alles
to check all the available checkboxes that are printed during the while loop
.
<form id="andere" name="andere" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<fieldset><legend>Selecteer de klassen waaraan je de persoon wilt koppelen:</legend>
<table>
<tr>
<td><input type="checkbox" id="alles" name="alles" value="">Selecteer alle klassen</td>
</tr>
<tr>
<?php
$query='SELECT oc_klas.klascode, oc_klas.klas_ID FROM oc_klas ORDER BY oc_klas.klas_ID';
$result=mysqli_query($mysqli,$query) or die('<p>Kan query: '.$query.' niet uitvoeren.</p>');
$aantalRijen = mysqli_num_rows($result);
$KLASSEN_PER_RIJ = 10;
//bereken de colspan van de laatste kolom
$fill=$aantalRijen%$KLASSEN_PER_RIJ;
$fill=$KLASSEN_PER_RIJ-$fill;
$teller=1;
while($myrow=mysqli_fetch_row($result))
{
print('<td><input type="checkbox" id="klas'.$myrow[1].'" name="klas'.$myrow[1].'" value="'.$myrow[1].'">'.$myrow[0].'</td>');
if($teller%$KLASSEN_PER_RIJ==0)
{
print('</tr><tr>');
}
$teller++;
}
print('</tr></table>');
?>
Usually I rely on the onclick
function:
onclick="for(c in document.getElementsByName('klas')) document.getElementsByName('klas').item(c).checked = this.checked"
but since the ID's are not identical now, I'm not sure how to tackle this particular problem. Any ideas?
JSF h:selectBooleanCheckbox to work with iCheck library
Icheck is customized css for checkboxes http://ift.tt/1do44mv My question is anybody managed to set it up to work with JSF (h:selectBooleanCheckbox)
Label of Checkbox is wrong
my problem is that i have a and i have 2 list items with text but my text is inside my checkbox and i searched everywhere and didn't found an answer to that. All i want to do is have the text aligned to the right of the textbox and not inside it.
Here is some code to check it out:
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="col-xs-12 col-sm-4 col-md-4">
<div class="squaredTwo">
<asp:CheckBoxList
ID="squaredTwo"
CellPadding="5"
CellSpacing="5"
runat="server">
<asp:ListItem Text="Hello i'm fred" />
<asp:ListItem Text="Hello i'm mike" />
</asp:CheckBoxList>
</div>
</div>
</div>
CSS
.squaredTwo #squaredTwo {
margin-top: 5px;
}
.squaredTwo {
width: 24px;
height: 24px;
background: #f5f5f5;
background: -webkit-linear-gradient(top, #0099b5 0%, #0099b5 40%, #0099b5 100%);
background: -moz-linear-gradient(top, #0099b5 0%, #0099b5 40%, #0099b5 100%);
background: -o-linear-gradient(top, #0099b5 0%, #0099b5 40%, #0099b5 100%);
background: -ms-linear-gradient(top, #0099b5 0%, #0099b5 40%, #0099b5 100%);
background: linear-gradient(top, #0099b5 0%, #0099b5 40%, #0099b5 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );
position: relative;
}
.squaredTwo input[type=checkbox] {
margin-left: 5px;
}
.squaredTwo label {
cursor: pointer;
position: absolute;
width: 20px;
height: 20px;
left: 2px;
top: 2px;
background: -webkit-linear-gradient(top, #f5f5f5 0%, #f5f5f5 100%);
background: -moz-linear-gradient(top, #f5f5f5 0%, #f5f5f5 100%);
background: -o-linear-gradient(top, #f5f5f5 0%, #f5f5f5 100%);
background: -ms-linear-gradient(top, #f5f5f5 0%, #f5f5f5 100%);
background: linear-gradient(top, #f5f5f5 0%, #f5f5f5 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f5f5f5', endColorstr='#f5f5f5',GradientType=0 );
}
.squaredTwo label:after {
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
opacity: 0;
content: '';
position: absolute;
width: 12px;
height: 7px;
background: transparent;
top: 5px;
left: 4px;
border: 3px solid #0099b5;
border-top: none;
border-right: none;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
transform: rotate(-45deg);
}
.squaredTwo label:hover::after {
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";
filter: alpha(opacity=30);
opacity: 0.3;
}
.squaredTwo input[type=checkbox]:checked + label:after {
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
filter: alpha(opacity=100);
opacity: 1;
}
JQuery Validation - Submit checkbox selected options
I am working with the JQuery validate plugin. All my validation works fine, but I am having difficulties passing the selected values of checkbox's to my PHP file. At the moment I have
var validator = $("#my_form").validate({
rules: {
'checkbox[]': {
atLeastOneChecked: true
}
},
messages: {
'checkbox[]': {
atLeastOneChecked: jQuery.validator.format("Please select at least one type of switch")
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "php/process.php",
data: {
'checkbox[]': $("#checkbox").val()
},
dataType: "json"
}).done(function (response) {
});
return false;
}
});
How can I pass the selected checkbox options in my submitHandler? I know I could just send a serialized form, but I have to submit data separately.
Thanks
How to allow only one checked box in the gridview?
If i have a grid view contains checkbox
chk_short_day as template field :
<asp:GridView ID="grv_week_day" runat="server" AutoGenerateColumns="False"
CssClass="datatable" OnRowDataBound="grv_week_day_RowDataBound" >
<Columns>
<asp:TemplateField HeaderStyle-Height="40px" HeaderStyle-Width="200px">
<HeaderTemplate>
<h2>week days
</h2>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbl_weekday" runat="server" CssClass="title" Text='<%# Bind("WeekDay") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Height="40px" Width="100px"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Height="40px">
<HeaderTemplate>
<h2>Attendance Type</h2>
</HeaderTemplate>
<ItemTemplate>
<asp:DropDownList ID="drp_att" runat="server" AutoPostBack="True" Width="200px" Enabled="false"
CausesValidation="false" OnSelectedIndexChanged="OnSelectedIndexChanged_drp">
</asp:DropDownList>
</ItemTemplate>
<HeaderStyle Height="40px"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Height="40px">
<HeaderTemplate>
<h2>From
</h2>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbl_From" runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle Height="40px"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Height="40px">
<HeaderTemplate>
<h2>To
</h2>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbl_To" runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle Height="40px"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Short Day">
<ItemTemplate>
<asp:CheckBox ID="chk_short_day" runat="server" AutoPostBack ="true" OnCheckedChanged="chk_short_day_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
How to allow only one checked in the gridview , If the user check one of the check boxes ,i want to uncheck the rest automatically .?
Save multiple checkbox on update post meta in wordpress
I have the same problem resolved in:
How to save multiple checkbox on update post meta in wordpress?
I have a cpt (clinica) with a multiple checkbox metabox.
I created the metabox:
add_meta_box('custom-meta-box', 'Music', 'music_meta_box', 'clinica', 'advanced', 'core');
Used the code suggested, but I'm getting the error:
Warning: in_array() expects parameter 2 to be array, boolean given in C:\wamp\www\dwa\wp-content\plugins\network-cliniche\network-cliniche.php on line 86
What am I doing wrong?
jQuery get clicked checkbox from array of checkboxes with the same name/id
I have a Razor View (ASP.NET MVC) on which I have a set of pre-validations that are used to set the state of a number of checkboxes.
While the normal functioning is OK, I really want to capture the click on only one specific checkbox (rather than the whole set of checkboxes) and do a ´$.post(...)´ call.
How will I be able to achieve this? Is this even possible?
Here's (part of) my View:
<div class="ukejuni">
@{
DateTime thisWeek = (DateTime)ViewData["thisWeek"];
int thisWeekNumber = DateTimeExtender.WeekOfYearIso8601(thisWeek);
int year = thisWeek.Year;
string chkValue = thisWeekNumber + ";" + year;
}
Uke @Html.Raw(thisWeekNumber.ToString())
@{
switch ((DeliveryWeekType)Model.ba.delivery_week_type)
{
case DeliveryWeekType.EvenWeek:
if (BusinessWeek.IsEvenWeek(thisWeekNumber)
&& (Model.ba.deviations.Where(deviation =>
deviation.agreement_id == Model.ba.agreement_id
&& deviation.week_nr == thisWeekNumber
&& deviation.year == year
&& deviation.delivery.HasValue
&& (bool)deviation.delivery == true)
.FirstOrDefault() == null)
)
{
<input class="leveringicon" type="checkbox" name="chkDelivery" checked="checked" value="@chkValue" />
}
else
{
<input class="leveringicon" type="checkbox" name="chkDelivery" value="@chkValue" />
}
break;
case DeliveryWeekType.OddWeek:
if (!BusinessWeek.IsEvenWeek(thisWeekNumber)
&& (Model.ba.deviations.Where(deviation =>
deviation.agreement_id == Model.ba.agreement_id
&& deviation.week_nr == thisWeekNumber
&& deviation.year == year
&& deviation.delivery.HasValue
&& (bool)deviation.delivery == true)
.FirstOrDefault() == null)
)
{
<input class="leveringicon" type="checkbox" name="chkDelivery" checked="checked" value="@chkValue" />
}
else
{
<input class="leveringicon" type="checkbox" name="chkDelivery" value="@chkValue" />
}
break;
default:
if (Model.ba.deviations.Where(deviation =>
deviation.agreement_id == Model.ba.agreement_id
&& deviation.week_nr == thisWeekNumber
&& deviation.year == year
&& deviation.delivery.HasValue
&& (bool)deviation.delivery == true)
.FirstOrDefault() == null)
{
<input class="leveringicon" type="checkbox" name="chkDelivery" checked="checked" value="@chkValue" />
}
else
{
<input class="leveringicon" type="checkbox" name="chkDelivery" value="@chkValue" />
}
break;
}
}
</div>
And this is the script I'm using to capture (and write to the console) the value of the checkbox:
$(document).ready(function () {
$("input[name='chkDelivery']").change(function (e) {
var values = $(this).val().split(';');
console.log(values);
if ($(this).is(':checked'))
{
@*$.post('@Html.Action("ChangeWeekDelivery")', {week: values[0], year: values[1], checkedState: true }, function () {
});*@
}
});
});
Whenever I see the console output I'll get 8 entries with the same output (8 is the number of checkboxes on the screen):
["51", "2015"]
["51", "2015"]
["51", "2015"]
["51", "2015"]
["51", "2015"]
["51", "2015"]
["51", "2015"]
["51", "2015"]
So, how do I limit the capture event to a single item? I've tried using ´$(e.target)´ but the result is still the same.
Best Regards
jquery if any checkbox is checked
There are many questions regarding checked checkbox , but this is somewhat different.
I want to display a css property if any checkbox is checked by the user. And if the user un-checks all the checkbox that css property should be removed.
I found this code
if (jQuery('#frmTest input[type=checkbox]:checked').length > 0) {
$(".css-check").css("background-color", "yellow");
} else {
$(".css-check").css("background-color", "pink");
}
<script src="http://ift.tt/1oMJErh"></script>
<form id="frmTest">
<input type="checkbox" name="vehicle" value="Car" class="test">I have a car
<br>
<input type="checkbox" name="vehicle" value="Car" class="test">I have a bike
<br>
<input type="checkbox" name="vehicle" value="Car" class="test">I have nothing
<br>
</form>
<div class="css-check">TEST</div>
But this only works when i place checkbox="true".
In Short:
if no checkbox is checked by user , background-color should be pink. And if even one checkbox is checked background-color should be yellow.
How to mark checkbox as selected using Bitwise in CakePHP?
I am developing an application in CakePHP 2.6 and I have a form where a user can set a series of flags when creating a calendar event.
I have managed to set up the 'add' action to display the flags and to also loop through in the controller after validation and save the value into my table. This process is done using bitwise. Code example below:
'add' action view:
echo $this->Form->input('flag', array('label' => false, 'type' => 'select', 'multiple' => 'checkbox', 'options' => $flagtypes, 'hiddenField' => false));
'add' action controller:
$flags = 0;
foreach ($data['flag'] as $r) {
$flags |= (int)$r;
}
I am however having trouble getting the checkboxes for the flags to be marked as selected in the edit action view when they are displayed.
'edit' action view:
echo $this->Form->input('flag', array('label' => false, 'type' => 'select', 'multiple' => 'checkbox', 'options' => $flagtypes, 'hiddenField' => false, 'checked' => $results[0]['BitwiseFlag']));
$results[0]['BitwiseFlag'] = 32 in the table.
$flagtypes array:
array(2) { [32]=> string(4) "Test" [64]=> string(9) "Testing 2" }
how to hide and show text if checkbox is checked vb.net
So far my codes are like this and they only enable and disable the Textbox.
Private Sub CheckBox17_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox17.CheckedChanged If CheckBox17.Checked = True Then
TextBox1.Enabled = False
ElseIf CheckBox17.Checked = False Then
TextBox1.Enabled = True
End If
End Sub
End Class
I need some codes that hide the text when the checkbox is checked and show it when checked.
Winforms: Change checked value in datagridview checkbox cell based on dialog result
I have a situation here. I have CheckBox column in DataGridView and it is checked by default (when the form loads). Now I have MessageBox for the confirmation that will pop up when someone wants to uncheck CheckBox. So when the DialogResult returns cancel, it should come back to normal state (previous value) and once DialogResult returns OK, it should uncheck. I have tried many cell events which doesn't suit my situation all will fire after cell change its value. I want to trigger snippets before it changes the value.
Thanks in advance.
dimanche 29 novembre 2015
JavaScript Calculating wrong
I am trying to perform calculation using JavaScript. When user enter less than 10 pages in input (#page) the cost is 1. if he adds more than 10, each page costs .10. there are 2 options for checkbox, if he clicks first checkbox 10 is added and second checkbox 15 is added.
This is working when it is done in sequential steps. (input then clicking checkbox).
Ex: Input is : 9 (total: 1) click checkbox1 - duplicates (total : 11) click checkbox1 - laser (total: 26)
Now if i change the Input to 11, then the total becomes 1.10 - even if both the checkboxes are checked.. (expected result should be - 26.10)
I am not sure how to do this...can anyone help me out
<html>
<head>
<title>Calculation</title>
</script>
<script>
function calculate()
{
var pages=document.getElementById("page").value;
if(pages <=10)
{
total.value=1;
}
if(pages >=11)
{
var extra_pages= pages - 10;
var new_total= extra_pages * .10;
var new_total1= 1 + new_total;
total.value= new_total1;
}
}
function checkbox1()
{
if(document.getElementById("ckbox1").checked === true)
{
var total1=document.getElementById("total").value;
const add1 = 10;
var check1 = +total1 + +add1;
total.value=check1;
}
if(document.getElementById("ckbox1").checked === false)
{
var total1=document.getElementById("total").value;
const sub1 = 10;
var check2 = +total1 - +sub1;
total.value = check2;
}
}
function checkbox2()
{
if(document.getElementById("ckbox2").checked === true)
{
var total1=document.getElementById("total").value;
const add1 = 15;
var check1 = +total1 + +add1;
total.value=check1;
}
if(document.getElementById("ckbox2").checked === false)
{
var total1=document.getElementById("total").value;
const sub1 = 15;
var check2 = +total1 - +sub1;
total.value = check2;
}
}
</script>
<body>
Enter a Number: <input type="text" id="page" value="1" oninput="calculate()">
<br>
<br><br><br><br>
duplicates <input type="checkbox" id="ckbox1" onclick="checkbox1()">
laser print: <input type="checkbox" id="ckbox2" onclick="checkbox2()"> <br><br>
</body>
</html>
Spring MVC checkboxes HTTP Status 400 The request sent by the client was syntactically incorrect
I have this simple form with 2 checkboxes and a submit button. When I submit the form, I get this 'HTTP Status 400 The request sent by the client was syntactically incorrect.' error. Someone please help!
This is my POJO:
public class Menu
{
private String day;
private String name;
private int price;
public Menu(){
}
public Menu(String day, String name, int price) {
this.day = day;
this.name = name;
this.price = price;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDay() {
return day;
}
public void setDay(String l) {
this.day = l;
}
@Override
public int hashCode() {
int hash = 3;
hash = 7 * hash + this.day.hashCode();
hash = 7 * hash + this.name.hashCode();
return hash;
}
@Override
public boolean equals(Object object) {
boolean result = false;
System.out.println("ARE YOU EVER CALLLED HOW MANY TIMES");
if (object == null || object.getClass() != getClass()) {
result = false;
} else {
Menu sc = (Menu) object;
if (this.day == sc.getDay() && this.name == sc.getName()
&& this.price == sc.getPrice()) {
result = true;
}
}
return result;
}
This is my Order class:
public class Order {
private List<Menu> menus = new ArrayList<Menu>();
public Order(){
}
public Order(ArrayList<Menu> menus){
this.menus = menus;
}
public List<Menu> getMenus() {
return menus;
}
public void setMenus(ArrayList<Menu> menus) {
this.menus = menus;
}
}
And this is my controller:
@Controller
public class RestaurantController {
@RequestMapping(value = "/menu", method = RequestMethod.GET)
public String menuPage(Model model)
{
Order o = new Order();
ArrayList<Menu> m = new ArrayList<Menu>();
m.add(new Menu("Sunday", "Phir Aloo", 12));
m.add(new Menu("Sunday", "Phir Cholay", 9));
model.addAttribute("today", m);
model.addAttribute("order", o);
return "/menu";
}
@RequestMapping(value = "/confirm", method = RequestMethod.POST)
public String done(@ModelAttribute(value="order") Order order, Model model)
{
return "/confirm";
}
And this is my JSP:
<form:form modelAttribute="order" method="post" action="/res/confirm">
<c:forEach items="${today}" var="r">
<form:checkbox path="menus" value="${r}" label="${r.name } ${r.price }" />
</c:forEach>
<input type="submit" value="Submit Data">
</form:form>
Now I just expect Class Order's property menus to be filled with selected checkboxes instead I get this error "The request sent by the client was syntactically incorrect. I have looked up every possible answer on this website but nothing seems to be solving the problem. Please help!
Set Checkbox on a Table Header
I created an application on Netbeans using Netbeans GUI Designer. What I want to do is basically I have created a table and I want one of the headers of the columns to have checkbox to select or deselect all the boolean checkboxes on all rows.
I found many sources about this, however they show how to create the gui directly by code without using the Netbeans GUI designer. The problem with this, I could create what I want probably by coding it from scratch, but I don't want to spend time designing the application, so im using the netbeans gui designer.
So how could i do this? Netbeans create all the pre designs codes without me requiring to type any code to design it, but just for the header with checkbox is my problem, can someone help me out with this, sorry if I made it sound complex.
Feel free to ask me any questions :)
Regards, Emre.
ASP.NET C# Gridview not detecting checkboxes being checked.
What i'm trying to do is execute some code when a checkbox in a gridview is checked, with the code being executed row by row. I debugged the code and every time returns false despite the checkboxes being checked. The code i'm trying to execute works if the conditional statement is removed.
ShoppingCartButton is the focus, but including the load code just in case.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data.OleDb;
using System.Text.RegularExpressions;
public partial class results : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Regex rgx = new Regex("^[0-9A-Za-z ]+$");
var myconn = new OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings["GamesConnectionString"].ConnectionString);
StringBuilder sb2 = new StringBuilder();
string genre = Request["GenreDropdown"];
if (genre == "" || genre==null) genre = " ";
string platform = Request["PlatformDropdown"];
if (platform == "" || platform == null) platform = " ";
string title = Request["TitleSearch"];
if (title == "" || title==null)
{
title = " ";
}
string checkedout = Request["CheckedOutBox"];
if (checkedout ==null || checkedout == "")
{
checkedout = " ";
}
if (!rgx.IsMatch(title) || !rgx.IsMatch(platform) || !rgx.IsMatch(genre) || !rgx.IsMatch(checkedout))
{
Label1.Text = "Invalid Data";
Response.Redirect("search.aspx");
}
else
{
//used as a default value for both genre and platform
string DefaultVal = "All";
string StockVal = "0";
StringBuilder sb = new StringBuilder();
sb.Append("SELECT * FROM GAMETABLE WHERE (GameTitle LIKE '%" + title + "%' AND ");
SqlDataSource objDS = new SqlDataSource();
objDS.ProviderName = System.Configuration.ConfigurationManager.ConnectionStrings["GamesConnectionString"].ProviderName;
objDS.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["GamesConnectionString"].ConnectionString;
//checking the values of the optional fields
if (genre == DefaultVal || genre == " ")
{
genre = "";
}
else
{
sb.Append("Genre =" + genre + " AND ");
}
if (platform == DefaultVal || platform == " ")
{
platform = "";
}
else
{
sb.Append("Platform =" + platform + " AND ");
}
if (checkedout != " " || checkedout != null)
{
StockVal = checkedout;
}
sb.Append("NumberInStock >=" + StockVal + ")");
if (title == " " || title == null)
{
objDS.SelectCommand = "select * from GameTable";
GridView1.DataSource = objDS;
GridView1.DataBind();
}
else
{
string sample = sb.ToString();
objDS.SelectCommand = sample;
GridView1.DataSource = objDS;
GridView1.DataBind();
}
foreach (GridViewRow row in GridView1.Rows)
{
string unpredictable1 = row.Cells[1].Text;
string unpredictable = row.Cells[8].Text;
sb2.Append(unpredictable1);
// if (unpredictable == "0")
// {
/// row.Cells[0].Controls.Clear();
// }
}
Label2.Text = sb2.ToString();
if (Session["UserID"] == null)
{
ShoppingCartButton.Visible = false;
}
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void ShoppingCartButton_Click(object sender, EventArgs e)
{
Label1.Text = "HIH0HI";
OleDbConnection myconn = new OleDbConnection();
myconn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|ProjectDatabase.accdb";
string UserID = Session["UserID"].ToString();
StringBuilder sb3 = new StringBuilder();
foreach (GridViewRow row in GridView1.Rows)
{
{
string unpredictable = "";
bool hi = true;
unpredictable = row.Cells[1].Text;
CheckBox chk = row.Cells[0].Controls[1] as CheckBox;
hi = chk.Checked;
sb3.Append(hi.ToString());
if (hi==true)
{
string command1 = "insert into Cart ([Username],[GameID]) values (@Username, @GameID)";
OleDbCommand cmd = new OleDbCommand(command1, myconn);
cmd.Parameters.AddWithValue("@Username", UserID);
cmd.Parameters.AddWithValue("@GameID", unpredictable);
myconn.Open();
cmd.ExecuteNonQuery();
myconn.Close();
}
}
Label1.Text = sb3.ToString();
}
}
}
Markup for the button and the gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" EmptyDataText ="Data Entry Error">
<Columns>
<asp:TemplateField HeaderText ="Add to Cart?">
<ItemTemplate>
<asp:CheckBox ID="checkbx" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button runat="server" id="ShoppingCartButton" Text="Add to shopping cart" OnClick="ShoppingCartButton_Click" />
Checkbox & Radio button Bootstrap CSS in ASP.net Update Panel
I used this template for my ASP.net admin application: http://ift.tt/1XB38NE
And I used the checkboxes and the radio buttons like in the template (regular Bootstrap checkboxes and radio buttons). Everything works fine, but there's one place where I must put them into a Update Panel and when I open the page the first time, the checkboxes and radio buttons look fine. But when I submit and the Update Panel refreshed the content, every checkbox or radiobutton has lost its css (or js?) and they look like the default controls when they are not stylized.
What can I do so the css (or js?) are not lost on every update in the Update Panel? I tried with putting the css and js links again in the child page (because it's now in the master page) but without success.
Angularjs Accordion behaviour if checkbox inside heading clicked
I have a checkbox in the angularjs accordion heading
<uib-accordion>
<uib-accordion-group heading="{{group.title}}" ng-repeat="items in itemData">
<uib-accordion-heading>
<checkbox ng-model="checkboxModel" ng-click="$event.stopPropagation();"></checkbox>Heading1 <i class="pull-right glyphicon" ng-class="{'glyphicon-menu-down': status.open, 'glyphicon-menu-right': !status.open}"></i>
</uib-accordion-heading></uib-accordion-group>
</uib-accordion>
When the checkbox is clicked on the accordion heading, the accordion item is getting expanded, Just want the checkbox to be selected without the accordion action. The accordion expansion should happen only when the heading/arrow is clicked not checkbox selected.
Tried giving this on checkbox tag
$event.stopPropogation()
, but doesnt seem to work.
PHP check boxes as boolean values
I need to create a Preferences table in a SQL using data from checkboxes. That is Pool,Jacuzzi, Backyard, Smart House are columns in Preferences that are TINYINTS to represent Boolean T or F. When a user checks a box, I want the value to be 1, else it stays at 0. So say a user wants a Pool and a Backyard and checks those two boxes. my $_POST[preferences] would be an array that would be [1,0,1,0].
<input type="checkbox" name="preferences[]" value="Pool"> Pool<br>
<input type="checkbox" name="preferences[]" value="Jacuzzi"> Jacuzzi<br>
<input type="checkbox" name="preferences[]" value="Backyard"> Backyard<br>
<input type="checkbox" name="preferences[]" value="Smart"> Smart House<br>
PHP form handling of checkbox values to cart
I have what seems to be a unique situation. I would like to have a check box form that shows on a page:
Exam Study Guide - Add $100.00 "check box here" Online Test Simulator - Add $200.00"check box here"
I would like to be able to choose either box or both and have the total dollar amount sent to my shopping cart via a submit button.
I have been trying to create an array and then add the amounts within the array so that they can be passed to the cart somehow. This is as far as I have gotten, the echo was a test to see if the process worked...it did not.
I was thinking that I could do a form action to create the array, then process that array giving me a number that could then be passed to the shopping cart.
if (isset($post['h'])){
$a=array(h);
echo array_sum($a);
}
Exam Study Guide - Add $100.00Online Test Simulator - Add $100.00
Comparing data from 2 arrays VB
Can I compare 2 arrays to check for a active checkbox in Visual Basic? There's one array that collects all the checkboxes in a vertical column and then the other array collects the checkboxes in a horizontal column. I'm not very good with VB so could you simplify the answer for me please.
Dim Choice1(4) As Integer
Choice1(0) = chkbocsYmg1Choice1.Checked
Choice1(1) = chkbocsYmg2Choice1.Checked
Choice1(2) = chkbocsYmg3Choice1.Checked
Choice1(3) = chkbocsYmg4Choice1.Checked
Choice1(4) = chkbocsYmg5Choice1.Checked
Choice1(4) = "1"
That's the vertical column
Dim Line1(4) As Integer
Line1(0) = chkbocsYmg1Choice1.Checked
Line1(1) = chkbocsYmg1Choice2.Checked
Line1(2) = chkbocsYmg1Choice3.Checked
Line1(3) = chkbocsYmg1Choice4.Checked
Line1(4) = chkbocsYmg1Choice5.Checked
That's the horizontal column. It's a 5x5 grid of checkboxes with only one checkbox that's true in a horizontal and vertical lineup.
if checkbox checked change the select options
I would like to generate selects options depends on checkbox. Like I have checkbox with 3 values: Film, Videoclip, Serial and form. When I click "Film" I would like to have with option: Comedy, Horror & when I "Videoclip" will change values to: Hip-Hop, Pop.
I'm trying for a few hours with javascript & jquery but still nothing :/
AngularJS CheckItems selected Items to Delete as HTTP Request
I want to use a Button Click, so when this Button gets clicked
<button type="button" ng-click="delete()">Delete</button>
to use this function,
$scope.delete = function() {
for( i=0; <each selected Item , i++)
I dont know how to code this in Javascript, but lets say 10 Items are selected with the Checkbox and I want to make 10 Http Delete Requests the Parameter ID of the Selection needed as a Parameter for the Rest Service . Username and Password are saved somewhere else.
$http.get("https://localhost/delete?username=" + $scope.email1 + "&password=" + $scope.password1 +&scope.selectedItemID).success(function(response)
}
})
This is the Html File:
<tr ng-repeat="Object in ObjectList track by $index">
<td>
<input type="checkbox" ng-model="Object.isCheck" ng-change="checkChange(Object)"/>
</td>
<td>{{ Object.idObject}}</td>
<td>{{ Object.messageObject }}</td>
</tr>
</tbody>
</table>
</div>
How to find state of dynamic checkbox using ExpandableListView using parent and child from HashMap
I've been reading all around the web for days, and tried different methods on end to get the state of the checkboxes, but I'm finding it tough to apply it to my android application.
I need help on how to find the state of a checkbox dynamically filled with 'child' values in an ExpandableListView. Unfortunately, I have found myself at a dead end, and quite disheartened that I haven't been able to apply it correctly to my application.
In my program, I would like to see which CheckBox is ticked when a 'Submit' button is clicked, and use the text value of the checked box to retrieve important results.
Does anybody have an easy method to keep track of which checkboxes are clicked in my expandable listview?
The activity:
public class meal extends Activity {
HashMap<String, List<String>> Meal_Category;
List<String> Meal_list;
ExpandableListView Exp_list;
MealAdapter adapter;
dataGenerator dg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Meal_Category = new HashMap<>();
setContentView(R.layout.activity_meal);
Exp_list = (ExpandableListView) findViewById(R.id.exp_list);
Log.d("myTag", "This is my message");
dg = new dataGenerator();
try {
//TODO -- chuk mods
dg.context = this;
Meal_Category = dg.getInfo();
//TODO -- end
} catch (Exception e) {
e.printStackTrace();
}
Log.d("mealCat", Meal_Category.toString());
Meal_list = new ArrayList<String>(Meal_Category.keySet());
adapter = new MealAdapter(this, Meal_Category, Meal_list);
Exp_list.setAdapter(adapter);
}
}
The adapter for the expandablelistview:
public class MealAdapter extends BaseExpandableListAdapter {
private Context ctx;
private HashMap<String, List<String>> Meal_Category;
private List<String> Meal_List;
public MealAdapter(Context ctx, HashMap<String, List<String>> Meal_Category, List<String> Meal_List )
{
this.ctx = ctx;
this.Meal_Category = Meal_Category;
this.Meal_List = Meal_List;
}
//Hashmap for keeping track of checkbox check states
@Override
public Object getChild(int parent, int child) {
return Meal_Category.get(Meal_List.get(parent)).get(child);
}
@Override
public long getChildId(int parent, int child) {
// TODO Auto-generated method stub
return child;
}
@Override
public View getChildView(int parent, int child, boolean lastChild, View convertview,
ViewGroup parentview)
{
String child_title = (String) getChild(parent, child);
if(convertview == null)
{
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertview = inflator.inflate(R.layout.child_layout, parentview,false);
}
CheckBox child_cb = (CheckBox) convertview.findViewById(R.id.child_txt);
child_cb.setText(child_title);
return convertview;
}
@Override
public int getChildrenCount(int arg0) {
return Meal_Category.get(Meal_List.get(arg0)).size();
}
@Override
public Object getGroup(int arg0) {
// TODO Auto-generated method stub
return Meal_List.get(arg0);
}
@Override
public int getGroupCount() {
// TODO Auto-generated method stub
return Meal_List.size();
}
@Override
public long getGroupId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getGroupView(int parent, boolean isExpanded, View convertview, ViewGroup parentview) {
// TODO Auto-generated method stub
String group_title = (String) getGroup(parent);
if(convertview == null)
{
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertview = inflator.inflate(R.layout.parent_layout, parentview,false);
}
TextView parent_textview = (TextView) convertview.findViewById(R.id.parent_txt);
parent_textview.setTypeface(null, Typeface.BOLD);
parent_textview.setText(group_title);
return convertview;
}
@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isChildSelectable(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
}
The activity_main xml
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp">
<ExpandableListView
android:id="@+id/exp_list"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft"
android:divider="#A4C739"
android:dividerHeight="0.5dp"
></ExpandableListView>
<Button
android:id="@+id/bSubmit"
android:text="Submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="105dp"
android:onClick="finalSelection"
/>
</RelativeLayout>
The child_layout activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<CheckBox
android:id="@+id/child_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:onClick="selectItem"
/>
</LinearLayout>
samedi 28 novembre 2015
SpringMVC Checkbox Always Submitted as TRUE, even if unchecked. Bound to a boolean
My Model object contains a 'boolean' field called expanded, the getters/setters are as follows.
private boolean expanded = false;
public boolean isExpanded() {
return expanded;
}
public void setExpanded(final boolean expanded) {
this.expanded = expanded;
}
JSP:
<form:checkbox path="expanded" />
Even after I uncheck the box on the form and submit, the generated HTML always has this. Note the auto-added Hidden field for FALSE values, it's already there. And note the checkbox is always value=TRUE, checked=CHECKED.
<input id="expanded1" name="expanded" type="checkbox" value="true" checked="checked"/>
<input type="hidden" name="_expanded" value="on"/>
Thus, the value of "Expanded" is always submitted as TRUE even when I uncheck the box. Is there a problem with binding? There are no binding errors, it finds the property.
I found this thread about unchecked checkboxes not being submitted by the browser, but SpringMVC has already added the Hidden field for me. I shouldn't have to do anything extra: Why spring always resolves <form:checkbox> to true?
Why is the proper FALSE value of the checkbox still not getting transmitted?
I verified in jQuery that immediately after form submission, it's already TRUE. There is no JS modifying the value anywhere.
Enable certain feature on checkbox checked android
This is my first question so please bear it! Okay, I'm working on an android app with multiple activities and these activities use WebView
(every activity uses webview instead of the main and settings.) I want to implement a function in all of activities which contains webview. Basically I want to implement a function (Options menu) which will be displayed when the user scrolls from right to left (the webview fills all the screen so user will scroll from right to left on webview). I found how to implement this function in my app thanks to the second answer here but I want to enable this option only when the checkbox (which I want to put in the Settings activity) is checked. So if the checkbox (call it check_left_to_right
) is checked: the left to right feature to open option menu is enabled (I'm hiding the actionbar in all webview activities so I will create the list view which will be on visibility.GONE by default. Let's call it option_list
). When checkbox isn't checked: left to right swipe to open options listview is disabled. The problem is that I don't know how to implement it so that this checkbox feature will control the scroll feature to be enabled or disabled. Please provide a detailed answer because I'm new to Programming (not n00b ;)). Thanks
Change background of parent when checkbox is checked
I am trying to alter the background of the parent element of a checkbox when it is checked.
Here is my JS:
var $boxes = $('#delivery-address-edit-modal .modal-dialog .modal-content .modal-body form label input[type="checkbox"]');
$boxes.each(function() {
if ($(this).is(":checked")) {
$(this).closest('label').toggleClass(".checked-checkbox-parent");
}
});
#delivery-address-edit-modal .modal-dialog .modal-content .modal-body form label input[type="checkbox"] {
position: absolute;
top: -9999px;
left: -9999px;
}
#delivery-address-edit-modal .modal-dialog .modal-content .modal-body form label {
display: block;
background: #C99C49;
margin: 10px 0;
cursor: pointer;
padding: 20px;
}
.checked-checkbox-parent {
background: black;
}
<label for="one-month">
<input id="one-month" type="checkbox">
<span>Monthly</span>
<span class="pull-right">(£30/case)</span>
<div class="clearfix"></div>
</label>
In the DOM viewer on chrome, things are as I would expect:
form > label > checkbox
So when I run my JS and a checkbox is checked, I expect the background property of the label to change to black and when it is unchecked, I expect it to go back to normal.
Multiple Form checkbox results used in mysqli select
I want to integrate checkboxes with my SQL select statement but I'm not sure how to convert the array into a usable select.
<form method="post">
<input name="searchterm" type="search" placeholder="Enter Search Terms Here" />
<input name="searchbtn" type="submit" value="Karaoke Search" />
<input name="checkbx[]" type="checkbox" checked value="Chartbuster" />
<label>Chartbuster</label>
<input name="checkbx[]" type="checkbox" checked value="Sound Choice" />
<label>Sound Choice</label>
<input name="checkbx[]" type="checkbox" checked value="DKKaraoke" />
<label>DKKaraoke</label>
<input name="checkbx[]" type="checkbox" checked value="Sunfly" />
<label>Sunfly</label>
<input name="checkbx[]" type="checkbox" checked value="Karaoke Hits" />
<label>Karaoke Hits</label>
<?php
if(isset($_POST['searchterm']) and ($_POST['searchterm']!="")) {
$searchterm=($_POST['searchterm']);
$checkbx=($_POST['checkbx']);
$searchresults=$db->query("SELECT *
FROM 1KaraokeDJ
WHERE Artist LIKE '%$searchterm%'
AND Brand IN $checkbx
GROUP BY Artist,
Title,
Brand
ORDER BY Artist,
Title,
Disc LIMIT 100");
}
...
?>
...
</form>
Basically, limit the search where Brand in one of the selected checkboxes
Two value in one checkbox and insert it to database
i have a question. i have a checkbox form, and i want that checkbox give me two value. and after that, insert it to database phpMyadmin.
Can you guys tell me how to do it? Thank you in advance guys, your answer means a lot to me.
Using form.submit to validate checkbox section
I have a form with a name that is passed to the controller, and when the form is $valid I continue to process data. This used to work with radio buttons, but when I switched to checkboxes, the validation passes only when all checkboxes are selected. How can I make it so, selecting 1 makes the form valid? Code snippet for reference:
<form name="snippetForm" ng-submit="vm.submitForm(snippetForm)" novalidate>
<input type="checkbox" ng-model="vm.destination.1" ng-true-value="'1'" name="location" required >
<input type="checkbox" ng-model="vm.destination.2" ng-true-value="'2'" name="location" required >
<input type="checkbox" ng-model="vm.destination.3" ng-true-value="'3'" name="location" required >
</form>
vm.submitForm = function(form) {
if(form.$valid) {
console.log('Passes only when all checkboxes from form.location are selected')
}
}
vendredi 27 novembre 2015
Meteor: Insert Checkbox (as Boolean) into Sub-Schema (aldeed2)
I'm trying to insert the checkbox value (as boolean) into a subschema of my collection. Not clear on 1) how to pass the checkbox value (can do it for normal input field) and 2) how to insert into subschema. I am using collection2 and handlebars.
1-This is what I have in the HTML form that needs to be submitted:
`<div class="checkbox">
<label><input type="checkbox" id="byow" checked="{{isChecked}}" value="">Bring Your Own Wine</label></div>`
2-This is what I have in my helper (in controller) to get the value of the form and the checkbox value, submit it and call the method that inserts it into the collection:
`BackendController.events({
//Add Venue - Add New Venue Submit Form Helper
'submit #add-venue-form' : function(event) {
event.preventDefault();
var venueName = event.target.venueName.value;
var byow = event.target.byow.checked;
var params = {
venueName: venueName,
byow: byow
}
//Insert Venue
Meteor.call('addVenue', params);
toastr.success('VenueAdded');
Router.go('/admin/manage-venues')
}
3-This is my method that is called to insert into my Venues collection (first part) and the structure of my collection and sub-collection:
`Meteor.methods({
'addVenue': function (params) {
Venues.insert(params);
}
// MAIN SCHEMA for the Venues colleciton.
Schema.Venues = new SimpleSchema({
venueName: {
type: String,
label: "Venue Name",
max: 200,
optional: false
},
//Attach schema for venue attributes (cuisine type, amenities, etc)
venueAttributes: {
type: Schema.VenueAttributes,
optional: true
}
});
//schema for venue attributes. Attached to main schema
Schema.VenueAttributes = new SimpleSchema({
byow: {
type: Boolean,
optional: true
}
});
Would really appreciate any help - I've managed to get the venueName to be passed successfully (so all my permissions/pub/sub is correct) but stuck at checkbox and subcollection.
Thanks! Dan.
C# How to Serialize XML from text/checbox on a loop based on button click
I am trying to serialize values in a user control based on a button click: C# WinForm Validate Checkbox and Error if at least one is unselected
The serialzation is not unlike this
I have 1 problem and few questions.
The problem is, I cannot call this from within my foreach process on button click (it is outwith of this).
The questions:
I am defining a string for each checkbox upon check; the name in the string should be related to the public string used for the XML section, is this a sensible approach? e.g.
public static string CheckBoxString;
private void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked)
{
CheckBoxString = "SESSIONNAMEValue";
}
}
Next question:
If I have multiple user controls all writing to the same XML at various stages e.g. user control 1 writes the sessionname for each checkbox, two writes name for each checkbox, three writes time for each checkbox.
How should I best manage this? I didn't think update the file was the best approach but I didnt want to write everything back to the form to store and process at the end...
Example XML:
<CONFIG1>
<SESSIONNAME>SOMETHINGHERE</SESSIONNAME>
<NAME>NAMEHERE</NAME>
<DATETIME>DATE</DATETIME>
</CONFIG1>
<CONFIG2>
<SESSIONNAME>SOMETHINGHERE</SESSIONNAME>
<NAME>NAMEHERE</NAME>
<DATETIME>DATE</DATETIME>
</CONFIG2>
The best way to toggle severals UIButtons with same images
In my app I'm using UIButton as check button. I have around 10 UIButton which all should toggle between two Image. An image which shows a "x" and another which shows a check mark. I have an action event for each UIButton, but since all 10 UIButton toggle between two images, is there a way to achieve this the best way. Right now I only know this solution, where I have a Boolean flag for each button and when toggle I set the flag to either true or false. But for me this seems like a bad practice.
Example for one of the UIButton:
var MenuBtnSelect = false
func GlutenSelect(sender: AnyObject)
{
if(!MenuBtnSelect)
{
sender.setImage(UIImage(named: "CheckMark"), forState: .Normal)
MenuBtnSelect = true
}
else
{
sender.setImage(UIImage(named: "NotCheckMark"), forState: .Normal)
MenuBtnSelect = false
}
}
Put a checkbox in each table cell
I'm trying to add checkboxes to each cell in my table. If $columns['mything$record'] is equal to 1, I want a checkbox that's checked to show up. If $columns['mything$record'] is equal to 0, I want a blank checkbox to show up. I've created if statements which one can view below, but they don't put a checkbox in each table cell with the respective value, only one blank checkbox appears at the top of the page. How can I put checkboxes in each cell that are checked and unchecked based on the cell value?
$columns = array(
1 => array(
"selectFieldName" => "nrs.record nrRecord",
"resultFieldName" => "nrRecord",
"headerName" => "NT#",
"defaultSortOrder" => -1,
),
array(
"selectFieldName" => "nrs.title",
"resultFieldName" => "title",
"headerName" => "Title",
"defaultSortOrder" => 1,
),
);
$selectedColumnNumbers = array(1,2,3);
$counter=4;
foreach($shortNameArray as $record=>$name){
if($record>0){
$columns[]=array(
"selectFieldName" => "CASE WHEN $record IN (GROUP_CONCAT(dm_nr_links.dmRecord)) THEN 1 ELSE 0 END mything$record",
"resultFieldName" => "mything$record",
"headerName" => "$name",
"defaultSortOrder" => 1,
);
$selectedColumnNumbers[]=$counter;
$counter++;
if ($columns['mything$record'] == 1) {
echo "<input type='checkbox' name='PLJan' ";
echo "checked='checked'";
}
if ($columns['mything$record'] == 0) {
echo "<input type='checkbox' name='JLFeb' ";
}
}
}
symfony2 form with self-referencing multiple checkboxes aren't presented checked in twig
Im trying to build a form with $this->createFormBuilder
that based on a preselected supervisor supposed to show me the "vendedores' that he supervised and the others the are created but without supervisors assigned.
My queries created with query_builder works well because shows the correct data but for those that the supervisor "supervised" shows the correct data but with the checkboxes unchecked.
This is my form where "asignados" bring every user that is related to the preselected supervisor and "no_asignados" brings every user that is without supervisor assigned.
$data = array();
$formulario = $this->createFormBuilder($data)
->add('asignados', 'entity', array(
'class' => 'PDBundle:Usuario',
//'property' => 'nombre',
'expanded' => true,
'multiple' => true,
'query_builder' => function (EntityRepository $er) use ($supervisorId) {
return $er->createQueryBuilder('u')
->where('u.estado = :activo')
->andWhere('u.tipoUsuario LIKE :vendedor')
->andWhere('u.supervisor = :supervisorId')
->orderBy('u.nombre', 'ASC')
->setParameter('activo','ACTIVO')
->setParameter('vendedor', 'VENDEDOR%')
->setParameter('supervisorId', $supervisorId);
}
))
->add('no_asignados', 'entity', array(
'class' => 'PDBundle:Usuario',
//'property' => 'nombre',
'expanded' => true,
'multiple' => true,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.tipoUsuario like :vendedor')
->andWhere('u.supervisor is NULL')
->orderBy('u.nombre', 'ASC')
->setParameter('vendedor', 'VENDEDOR%');
}
))
->add('guardar', 'submit', array('label' => 'Guardar','attr' => array('class' => 'btn btn-primary',)))
->add('no_guardar', 'submit', array('label' => 'No guardar','attr' => array('class' => 'btn btn-danger',)))
->getForm();
This my usuario.php entity
<?php
namespace PD\AppBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\ExecutionContextInterface;
use Symfony\Component\Validator\Constraints as Assert;
use APY\DataGridBundle\Grid\Mapping as GRID;
/**
* Usuario
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="PD\AppBundle\Entity\UsuarioRepository")
*
*/
class Usuario implements UserInterface
{
/**
* Método requerido por la interfaz UserInterface
*/
public function eraseCredentials()
{
}
/**
* Método requerido por la interfaz UserInterface
*/
public function getRoles()
{
return array('ROLE_USUARIO');
}
/**
* Método requerido por la interfaz UserInterface
*/
//public function getUsername()
//{
// return $this->getEmail();
//}
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nombre", type="string", length=100)
* @GRID\Column(title="Nombre")
*/
private $nombre;
/**
* @var string
*
* @ORM\Column(name="apellidos", type="string", length=100)
* @GRID\Column(title="Apellidos")
*/
private $apellidos;
/**
* @var string
*
* @ORM\Column(name="username", type="string", length=100)
*/
private $username;
/**
* @var string
*
* @ORM\Column(name="password", type="string", length=100)
*/
private $password;
/**
* @var string
*
* @ORM\Column(name="salt", type="string", length=100)
*/
private $salt;
/**
* @var string
*
* @ORM\Column(name="email", type="string", length=100)
* @GRID\Column(title="Correo")
*/
private $email;
/**
* @var string
*
* @ORM\Column(name="direccion", type="text")
*/
private $direccion;
/**
* @var \DateTime
*
* @ORM\Column(name="fecha_alta", type="datetime")
*/
private $fechaAlta;
/**
* @var \DateTime
*
* @ORM\Column(name="fecha_nacimiento", type="datetime")
*/
private $fechaNacimiento;
/**
* @var string
*
* @ORM\Column(name="dui", type="string", length=9)
*/
private $dui;
/**
* @var string
*
* @ORM\Column(name="tipo_usuario", type="string", length=25)
* @GRID\Column(title="Rol")
*/
private $tipoUsuario;
/**
* @var boolean
*
* @ORM\Column(name="estado", type="string", length=20)
*/
private $estado;
/**
* @ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Usuario", inversedBy="supervisados")
* @ORM\JoinColumn(name="usuario_id", referencedColumnName="id")
* @Assert\Type(type="PD\AppBundle\Entity\Usuario")
* @GRID\Column(field="supervisor.nombre", title="Nombre supervisor")
* @GRID\Column(field="supervisor.apellidos", title="Apellido supervisor")
*/
protected $supervisor;
/**
* @ORM\OneToMany(targetEntity="PD\AppBundle\Entity\Usuario", mappedBy="supervisor", cascade={"persist"})
*/
protected $supervisados;
public function __construct()
{
$this->fechaAlta = new \DateTime();
$this->supervisados = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getNombreApellidos(){
return $this->getNombre().' '.$this->getApellidos();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* @param string $nombre
* @return Usuario
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set password
*
* @param string $password
* @return Usuario
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set salt
*
* @param string $salt
* @return Usuario
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Get salt
*
* @return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* Set direccion
*
* @param string $direccion
* @return Usuario
*/
public function setDireccion($direccion)
{
$this->direccion = $direccion;
return $this;
}
/**
* Get direccion
*
* @return string
*/
public function getDireccion()
{
return $this->direccion;
}
/**
* Set username
*
* @param string $username
* @return Usuario
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set fechaAlta
*
* @param \DateTime $fechaAlta
* @return Usuario
*/
public function setFechaAlta($fechaAlta)
{
$this->fechaAlta = $fechaAlta;
return $this;
}
/**
* Get fechaAlta
*
* @return \DateTime
*/
public function getFechaAlta()
{
return $this->fechaAlta;
}
/**
* Set fechaNacimiento
*
* @param \DateTime $fechaNacimiento
* @return Usuario
*/
public function setFechaNacimiento($fechaNacimiento)
{
$this->fechaNacimiento = $fechaNacimiento;
return $this;
}
/**
* Get fechaNacimiento
*
* @return \DateTime
*/
public function getFechaNacimiento()
{
return $this->fechaNacimiento;
}
/**
* Set dui
*
* @param string $dui
* @return Usuario
*/
public function setDui($dui)
{
$this->dui = $dui;
return $this;
}
/**
* Get dui
*
* @return string
*/
public function getDui()
{
return $this->dui;
}
public function __toString()
{
/*
* 1 = SUPER_ADMIN
* 2 = ADMIN administrador
* 3 = SUPERVISOR supervisor
* 4 = VENDEDOR vendedor de tickets
* 5 = VENDEDOR_INDEPENDIENTE vendedor de tickets independiente
*/
if($this->getTipoUsuario() == 'SUPER_ADMIN'){
return $this->getNombre().' '.$this->getApellidos(). ' (Super Admin)';
}
if($this->getTipoUsuario() == 'ADMIN'){
return $this->getNombre().' '.$this->getApellidos(). ' (Admin)';
}
if($this->getTipoUsuario() == 'SUPERVISOR'){
return $this->getNombre().' '.$this->getApellidos(). ' (Supervisor)';
}
if($this->getTipoUsuario() == 'VENDEDOR'){
return $this->getNombre().' '.$this->getApellidos(). ' (Vendedor)';
}
if($this->getTipoUsuario() == 'VENDEDOR_INDEPENDIENTE'){
return $this->getNombre().' '.$this->getApellidos(). ' (Vendedor Independiente)';
}else{
return $this->getNombre().' '.$this->getApellidos();
}
}
/**
* Set apellidos
*
* @param string $apellidos
* @return Usuario
*/
public function setApellidos($apellidos)
{
$this->apellidos = $apellidos;
return $this;
}
/**
* Get apellidos
*
* @return string
*/
public function getApellidos()
{
return $this->apellidos;
}
/**
* Set email
*
* @param string $email
* @return Usuario
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set tipoUsuario
*
* @param integer $tipoUsuario
* @return Usuario
*/
public function setTipoUsuario($tipoUsuario)
{
$this->tipoUsuario = $tipoUsuario;
return $this;
}
/**
* Get tipoUsuario
*
* @return integer
*/
public function getTipoUsuario()
{
return $this->tipoUsuario;
}
/**
* Set estado
*
* @param string $estado
* @return Usuario
*/
public function setEstado($estado)
{
$this->estado = $estado;
return $this;
}
/**
* Get estado
*
* @return string
*/
public function getEstado()
{
return $this->estado;
}
/**
* Set supervisor
*
* @param \PD\AppBundle\Entity\Usuario $supervisor
* @return Usuario
*/
public function setSupervisor(\PD\AppBundle\Entity\Usuario $supervisor = null)
{
$this->supervisor = $supervisor;
return $this;
}
/**
* Get supervisor
*
* @return \PD\AppBundle\Entity\Usuario
*/
public function getSupervisor()
{
return $this->supervisor;
}
/**
* Add supervisados
*
* @param \PD\AppBundle\Entity\Usuario $supervisados
* @return Usuario
*/
public function addSupervisado(\PD\AppBundle\Entity\Usuario $supervisados)
{
$this->supervisados[] = $supervisados;
return $this;
}
/**
* Remove supervisados
*
* @param \PD\AppBundle\Entity\Usuario $supervisados
*/
public function removeSupervisado(\PD\AppBundle\Entity\Usuario $supervisados)
{
$this->supervisados->removeElement($supervisados);
}
/**
* Get supervisados
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getSupervisados()
{
return $this->supervisados;
}
}
This is my twig file
{% extends '::base.html.twig' %}
{% block body %}
<h1 class="page-header">Agregar vendedores a supervisor</h1>
Empleado: {{ supervisor }}
{# <h3 class="page-header">Vendedores asignados</h3> #}
{{ form_start(formulario) }}
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading" data-toggle="collapse" {# data-parent="#accordion" #} href="#vendedores_asignados">
<h4 class="panel-title">
Vendedores asignados
</h4>
</div>
<div id="vendedores_asignados" class="panel-collapse collapse in">
<div class="panel-body">
<div class="row">
{% for supervisados in formulario.asignados %}
<div class="col-md-4">
{{ form_widget(supervisados) }}
{{ form_label(supervisados) }}
{{ form_errors(supervisados) }}
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
{# <h3 class="page-header">Vendedores</h3> #}
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading" data-toggle="collapse" {# data-parent="#accordion" #} href="#vendedores_sin_asignar">
<h4 class="panel-title">
Vendedores sin supervisor
</h4>
</div>
<div id="vendedores_sin_asignar" class="panel-collapse collapse in">
<div class="panel-body">
<div class="row">
{% for sinSupervisar in formulario.no_asignados %}
<div class="col-md-4">
{{ form_widget(sinSupervisar) }}
{{ form_label(sinSupervisar) }}
{{ form_errors(sinSupervisar) }}
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">{{ form_widget(formulario.guardar)}} {{ form_widget(formulario.no_guardar)}}</div>
<div class="col-md-4"></div>
</div>
{{ form_end(formulario) }}
{% endblock %}
Any idea or suggestion that can help to accomplish this? Thanks in advanced.
C# WinForm Validate Checkbox and Error if at least one is unselected
I seem to have a problem with validating my user control.
Help would be awesome :)
If I have at least one check box checked, I will process through a loop all checkboxes.
If I have no checkboxes checked, the form generates an error.
An if with just one checkbox before the foreach would be an easier solution for me but I have quite a lot of checkboxes on this user control and dont want to list them all....
Also I think there is some logic problem, cos even select a checkbox I still get my warning messagebox... and I the warning messagebox loops causing it never to close...
private void ValidateButton_Click(object sender, EventArgs e)
{
foreach (var control in this.Controls)
{
if (control is CheckBox)
{
if (((CheckBox)control).Checked)
{
//CODE GOES HERE to
//Process checked in background
//and then
validatebutton.hide();
nextbutton.show();
}
}
else
{
DialogResult uncheckederror = MessageBox.Show("You must select at least one checkbox",
"Validation Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
}
}
}
Rails checkbox not saving any value
I am new to Rails and I have these checkboxes that display the options just fine, but aren't changing anything in the database as the form is submitted. The form in views has the following piece of code:
<%= form_for(@sector) do |f| %>
<%= f.collection_check_boxes :admins_id, Admin.all, :id, :name %>
<% end %>
and this is the corresponding action in the sectors controller:
def update
@sector = Sector.find(params[:id])
@sector.admins_id = params[:admins_id]
respond_to do |format|
if @sector.update(sector_params)
format.html { redirect_to @sector, notice: 'Sector was successfully updated.' }
format.json { render :show, status: :ok, location: @sector }
else
format.html { render :edit }
format.json { render json: @sector.errors, status: :unprocessable_entity }
end
end
end
private
def sector_params
params.require(:sector).permit(:title, :admins_id)
end
And, finally, I have these relations in the models:
class Sector < ActiveRecord::Base
has_many :admins, dependent: :destroy
validates :title, presence: true
validates :title, uniqueness: true
end
class Admin < ActiveRecord::Base
belongs_to :sector
end
Also, I can create and assign admins just fine in the rails console.
TextField is not following the conditions
here's a quick explanation, I make my TextField into false condition inside of .setEnabled area. So basically after the user press check on Cake's check-box, he need to choose either one of the sub-item menu, after he do that, he needs to enter the quantity of the cake. But, after choosing the sub-item menu, the TextField condition should be true(means it should be editable), but it doesn't go as were told. Thank you.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
class testingcheckbox
{
public static void main(String[] args)
{
Frame qB = new Frame("Queen Bakery");
JCheckBox cake;
cake = new JCheckBox("Cake");
JCheckBox cakeOpt1 = new JCheckBox("Butter Cake");
JCheckBox cakeOpt2 = new JCheckBox("Cheese Cake");
TextField tfCake = new TextField();
tfCake.setPreferredSize(new Dimension(50,24));
tfCake.setEnabled(false);
ActionListener cakeListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(cake.isSelected())
{
cakeOpt1.setEnabled(true);
cakeOpt2.setEnabled(true);
if(cakeOpt1.isSelected())
{
tfCake.setEnabled(true);
}
else
{
tfCake.setEnabled(false);
}
}
else
{
cakeOpt1.setEnabled(false);
cakeOpt2.setEnabled(false);
}
}
};
cake.addActionListener(cakeListener);
qB.add(cake);
cakeOpt1.setEnabled(false);
cakeOpt2.setEnabled(false);
qB.add(cakeOpt1);
qB.add(cakeOpt2);
qB.add(tfCake);
qB.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent windowEvent)
{
System.exit(0);
}
});
qB.setSize(780,470);
qB.setLayout(new FlowLayout(FlowLayout.LEFT));
qB.setVisible(true);
qB.setLocationRelativeTo(null);
qB.setResizable(false);
}
}
How to make a new JSON object in a JSON array with a checkbox
I have a table that shows results with a checkbox at the end of each result. There is a checkbox that puts the chosen result into an object array. How do I make it so every time I check a box, a new object will be created within the object?
HTML:
<tbody>
<tr ng-repeat="t in student | orderBy:sortType:sortReverse | filter:query">
<td>{{ t.idPersoon }}</td>
<td>{{ t.voornaam }}</td>
<td>{{ t.tussenvoegsel }}</td>
<td>{{ t.achternaam }}</td>
<td>{{ t.email }}</td>
<td>
<div class="checkbox">
<label>
<input type="checkbox" data-checklist-model="user.studentid" data-checklist-value="t.idPersoon"">
</label>
</div>
</td>
</tr>
Controller
$scope.user = [{
studentid: [$scope.student] -1,
docentid: 'nhfb',
vakid: 'dea',
klasid: 'oose'
}];
So right now user will be shown as
{
[
studentid: "123",
studentid: "456",
studentid: "789"
],
tid: "nhfb",
vakid: "dea",
klasid: "oose"
}
but I want the structure to be
[{
studentid: "123",
docentid: "nhfb",
vakid: "dea",
klasid: "oose"
} {
studentid: "456",
docentid: "nhfb",
vakid: "dea",
klasid: "oose"
}]
How to fast render >10000 items using React + Flux?
I would like to ask what is the correct way to fast render > 10000 items in React.
Suppose I want to make a checkboxList which contain over dynamic 10000 checkbox items.
I make a store which contain all the items and it will be used as state of checkbox list.
When I click on any checkbox item, it will update the corresponding item by action and so the store is changed.
Since store is changed so it trigger the checkbox list update.
The checkbox list update its state and render again.
The problem here is if I click on any checkbox item, I have to wait > 3 seconds to see the checkbox is ticked. I don't expect this as only 1 checkbox item need to be re-rendered.
I try to find the root cause. The most time-consuming part is inside the checkbox list render method, related to .map which create the Checkbox component to form componentList.. But actually only 1 checkbox have to re-render.
The following is my codes. I use ReFlux for the flux architecture.
CheckboxListStore
The Store store all the checkbox item as map. (name as key, state (true/false) as value)
const Reflux = require('reflux');
const Immutable = require('immutable');
const checkboxListAction = require('./CheckboxListAction');
let storage = Immutable.OrderedMap();
const CheckboxListStore = Reflux.createStore({
listenables: checkboxListAction,
onCreate: function (name) {
if (!storage.has(name)) {
storage = storage.set(name, false);
this.trigger(storage);
}
},
onCheck: function (name) {
if (storage.has(name)) {
storage = storage.set(name, true);
this.trigger(storage);
}
},
onUncheck: function (name) {
if (storage.has(name)) {
storage = storage.set(name, false);
this.trigger(storage);
}
},
getStorage: function () {
return storage;
}
});
module.exports = CheckboxListStore;
CheckboxListAction
The action, create, check and uncheck any checkbox item with name provided.
const Reflux = require('reflux');
const CheckboxListAction = Reflux.createActions([
'create',
'check',
'uncheck'
]);
module.exports = CheckboxListAction;
CheckboxList
const React = require('react');
const Reflux = require('reflux');
const $ = require('jquery');
const CheckboxItem = require('./CheckboxItem');
const checkboxListAction = require('./CheckboxListAction');
const checkboxListStore = require('./CheckboxListStore');
const CheckboxList = React.createClass({
mixins: [Reflux.listenTo(checkboxListStore, 'onStoreChange')],
getInitialState: function () {
return {
storage: checkboxListStore.getStorage()
};
},
render: function () {
const {storage} = this.state;
const LiComponents = storage.map((state, name) => {
return (
<li key = {name}>
<CheckboxItem name = {name} />
</li>
);
}).toArray();
return (
<div className = 'checkbox-list'>
<div>
CheckBox List
</div>
<ul>
{LiComponents}
</ul>
</div>
);
},
onStoreChange: function (storage) {
this.setState({storage: storage});
}
});
module.exports = CheckboxList;
CheckboxItem Inside onChange callback, I call the action to update the item.
const React = require('react');
const Reflux = require('reflux');
const $ = require('jquery');
const checkboxListAction = require('./CheckboxListAction');
const checkboxListStore = require('./CheckboxListStore');
const CheckboxItem = React.createClass({
mixins: [Reflux.listenTo(checkboxListStore, 'onStoreChange')],
propTypes: {
name: React.PropTypes.string.isRequired
},
getInitialState: function () {
const {name} = this.props;
return {
checked: checkboxListStore.getStorage().get(name)
};
},
onStoreChange: function (storage) {
const {name} = this.props;
this.setState({
checked: storage.get(name)
});
},
render: function () {
const {name} = this.props;
const {checked} = this.state;
return (
<div className = 'checkbox' style = {{background: checked ? 'green' : 'white'}} >
<span>{name}</span>
<input ref = 'checkboxElement' type = 'checkbox'
onChange = {this.handleChange}
checked = {checked}/>
</div>
);
},
handleChange: function () {
const {name} = this.props;
const checked = $(this.refs.checkboxElement).is(':checked');
if (checked) {
checkboxListAction.check(name);
} else {
checkboxListAction.uncheck(name);
}
}
});
module.exports = CheckboxItem;