mercredi 31 décembre 2014

CheckBox in ChildView of ExpandableListView

In my android application, I have an ExpandableListView with each group having only one child, which contains a checkbox. I'm having trouble in setting the value of the checkboxes.


I'm retrieving the values of checkbox from database and storing it in an integer ArrayList with values 0 & 1 for checked and unchecked respectively



ArrayList<Integer> trustedList = new ArrayList<Integer>();


Initially, I've put all the entries in database as 1.


The Adapter class for ExpandableListView is as follows :



class DataAdapter extends BaseExpandableListAdapter {

private Context context;
LayoutInflater lat = getLayoutInflater();

CheckBox cb;

public DataAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}

@Override
public View getChildView(int group, int child, boolean arg2, View v,
ViewGroup arg4) {
// TODO Auto-generated method stub

v = lat.inflate(R.layout.inflate_list, null);
cb = (CheckBox) v.findViewById(R.id.checkBox1);

if (trustedList.get(group) == 1)
cb.setChecked(true);
else
cb.setChecked(false);

return v;
}
}


But I'm getting unchecked values for the checkboxes. Also, on checking the checkbox and collapsing and expanding the group, I'm getting unchecked checkbox again.


Please can somebody help me out??





Correct Way to Code a Group of Radio Buttons using RadioButtonFor

From what I can see, the correct way to define a checkbox for MVC is as follows.



@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)


This will display a checkbox, associate a label with the checkbox, and make the label clickable, which means clicking the label also toggles the checkbox.


But what happens with RadionButtonFor, where there can be many button/label combinations for the same model field? Using the approach above, there would be multiple elements with the same ID.


I have been researching this for a while now. I have found many solutions; however, they all seem to either not have a clickable label, or they require a bunch of custom and/or non-standard coding.


Did the designers of MVC recognize that we may want to have multiple radio buttons for the same field? And, if so, how is it supposed to be handled?





Listview and checkboxes - setting, checking, getting checked

I'm having an issue with checkboxes on a listview, checking items, and listing just those checked items. This is my first android app, and without knowing what all is needed here in the way of code to help figure it out, I have recreated the problem in a bare-bones app that demonstrates what is going on. I suspect it is in the getView() method, but I'm not really sure.


Problem One: When more items are in the list than are visible, checking items at the top of the list also checks items that are not visible.


Problem Two: In the onOptionsItemSelected method there are two ways I've tried to get just the checked items. One is currently commented out, but they both fail in different ways. There are comments above each method that expalins what goes wrong.


http://ift.tt/1toKWbH





Multiple loop conditions for a set of checkbox choices

Using CodeIgniter, I am creating an admin area where I am able to create footnotes for any given product line.


HTML



<p>Choose Product Line</p>
<label><input type="checkbox" name="productline[]" value="1" />Product One</label>
<label><input type="checkbox" name="productline[]" value="2" />Product Two</label>
<label><input type="checkbox" name="productline[]" value="3" />Product Three</label>
<label><input type="checkbox" name="productline[]" value="4" />Product Four</label>


PHP



for ( $i = 0; $i < count( $this->input->post( 'product[]' ) ); $i++ )
{
$line__id = $this->input->post( 'product' )[$i];

$footnote_data = array(
'line__id' => $line__id,
'code' => $this->input->post( 'footnotecode' ),
'text' => $this->input->post( 'footnotetext' ),
'status' => $this->input->post( 'status' ),
'createdon' => date( 'Y-m-d H:i:s' )
);

error_log( print_r( $footnote_data, true ) );
}


Which will output something like this:


LOG:



Array
(
[line__id] => 1
[code] => ABC123
[text] => Hello World
[status] => 1
[createdon] => 2014-12-31 22:28:59
)

Array
(
[line__id] => 2
[code] => ABC123
[text] => Hello World
[status] => 1
[createdon] => 2014-12-31 22:28:59
)
....


All is fine, I'm looping through each product line that was selected.


As you can see in the $footnote_data array, I have several other fields. They are simple text input fields, and are 1:1 with the current iteration of the loop $i.


I also have 2 other checkbox choices. You have to choose the product line (above) then enter the code and actual footnote text. Then, you have to choose what type of footnote this is.


HTML



<p>Footnote Type</p>
<label><input type="checkbox" name="footnotetype[]" value="awesome" />Awesome</label>
<label><input type="checkbox" name="footnotetype[]" value="cool" />Cool</label>
<label><input type="checkbox" name="footnotetype[]" value="average" />Average</label>


I can choose as many footnote types that I want for the current footnote I am creating. I'm just not sure the best way to dive into the second series of checkboxes (the type).


I have tried a nested loop within the main productline loop, but that didn't get the result(s) I was looking for. If I log the result I am looking for, this is what it would look like:


OUTPUT



Array
(
[line__id] => 2
[type] => Awesome
[code] => ABC123
[text] => Hello World
[status] => 1
[createdon] => 2014-12-31 22:28:59
)

Array
(
[line__id] => 2
[type] => Cool
[code] => ABC123
[text] => Hello World
[status] => 1
[createdon] => 2014-12-31 22:28:59
)

Array
(
[line__id] => 3
[type] => Average
[code] => ABC123
[text] => Hello World
[status] => 1
[createdon] => 2014-12-31 22:28:59
)

....


See how the same product line can have multiple footnote types? The actual record would/could be exactly the same for each product line selected. Only the type could be different.


Another thought I had - once the initial loop is done - and I have a footnote ID for the newly created footnote, do I turn right around and update the db for each footnote type? I'm talking myself in circles...


My DB structure looks like this:


DATABASE



footnote_id
type_id // this is the question
text
code
status
createdon


Thank you for your help!





Asp.net checkbox renders span with AutoPostBack = true in it

This has got me at my wit's end. I have a GridView with a column with a checkbox in it. The checkbox is set to call CheckedChanged and AutoPostBack is true.



<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cbNotifier" runat="server" OnCheckedChanged="cbNotifier_CheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>


I am using similar code in the first column of the GridView and it works perfectly. I am using the code above in a different column. It does not work. Instead of rendering the checkbox to do a postback, it renders a span around the checkbox like this:



<span AutoPostBack="true"><input id="cbNotifier" type="Checkbox"></span>


so, of course, the checkbox will not postback.


If I add another, identical checkbox to the same column, like this ...



<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cbNotifier" runat="server" OnCheckedChanged="cbNotifier_CheckedChanged" AutoPostBack="true" />
<asp:CheckBox ID="cbNotifier1" runat="server" OnCheckedChanged="cbNotifier_CheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>


... the second checkbox postsback perfectly, the first one gets the span tag around it. What on earth is going on?





How to remove the focus border of a CheckBox in C# Visual Studio?

Tried most properties and did not manage to completely disable the focus of a checkbox in visual studio. Does anyone know how to do it?





Checkbox value comes with single value

My code is working but there are problem if i choised both of value from form and then only single value added database. Where is going wrong.



<?php
$con = mysqli_connect('localhost', 'root', '12345', 'fruit');
if ($_SERVER['REQUEST_METHOD'] != 'POST' && !isset($_POST['submit'])) {
echo '<form action="" method="post">
<input type="checkbox" name="fruits[]" value="Apple" />APPLE<br />
<input type="checkbox" name="fruits[]" value = "Lemon" />LEMON<br />
<input type="submit" name="submit" value="POST">
</form>';
}elseif ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit'])){
$fruit = $_POST['fruits'];
foreach ($fruit as $fruits){
$fruits = mysqli_real_escape_string($con, strip_tags($fruits));
}
$sql_add = mysqli_query($con, "INSERT INTO fruit (name) VALUES ('$fruits')");
if (mysqli_affected_rows($con) == 1) {
echo "Ok not problem.";
}else {
echo "There are some problem. Please submit your choice again.";
}
}




Bootstrap multiselect dropdown checkbox not working on paginated table

I am having a dynamically populated paginated table. I am using "bootstrap multiselect checkbox " option in one of the column. This plugin works fine in first page of the table , but when i try to navigate to next pages on paginated table , "boostrap multiselect drop down checkbox options become a plain normal multiselect option without checkbox. Also search option is not working .Is there something missing here ?



<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="css/jquery.dataTables.min.css" type="text/css">
<link rel="stylesheet" href="css/bootstrap-multiselect.css" type="text/css">
<link rel="stylesheet" href="css/dataTables.bootstrap.css" type="text/css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/bootstrap-multiselect.js"></script>
<script type="text/javascript" src="js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="js/searchDataTable.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$('.applicationNameSelectClass').multiselect({
includeSelectAllOption : true ,
enableFiltering: true,
});
});
</script>

<script>
$(document).ready(function() {
$('#dbResultsTable').dataTable();
} );
</script>

<form id="form">
<table border="1" id="dbResultsTable" class="table table-striped" >
<!-- Dynamically populated table -->
</table>
<input type="submit" id="submitId"/>
</form>




mardi 30 décembre 2014

checkbox id replace from previous android java

I have created dynamically checkbox for each title like below:


door



  • wooden

  • aluminiun


window



  • wooden

  • aluminiun


I am getting title from this piece of code:



for (int i = 0; i < arr.length; i++) {
if (DValue.contains(arr[i])) {
DValue = DValue.replace(arr[i], "");
}
if (Title.contains(arr[i])) {
Title = Title.replace(arr[i], "");
}
}


and set checkbox id here:



for (int a = 0; a < data.length; a++) {
cb[a] = new CheckBox(this);
cb[a].setId(a);
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
(int) LayoutParams.WRAP_CONTENT,
(int) LayoutParams.WRAP_CONTENT);
param.leftMargin = 25;
// param.topMargin = (a + 1) * (105 + add1 -sub);
param.topMargin = add1;
cb[a].setPadding(45, 20, 25, 5); // cb[a].setPadding(5, 23, 5,
// // 5);
cb[a].setLayoutParams(param);
cb[a].setText(data[a].trim());
if (strMultiChk != null)
{
strMultiChk.replaceAll("\\s","");
String cb_text = cb[a].getText().toString();
String[] arr1 = TextUtils.split(strMultiChk, ";");
//String[] arr1 = strMultiChk.split("[")[1];
for(int i = 1; i < arr1.length; i++)
{
if(arr1[i].contains(Title) && strMultiChk.contains(cb_text))
{
cb[a].setChecked(true);
}
}
}
layout.addView(cb[a]);
// add = add + 25;
// add1 = add1 + 15;
add1 = add1 + 35;
}


the problem is that it set both checkbox for 1st title i.e door but for 2nd title i.e window it replace the id of both checkboxes from previous two:


Kindly suggest me, how can I resolve it.


waiting for reply.


Thanks.





Checkboxes aligned in a row

Bear with me as I'm not well versed with front end design. How can I get the following checkboxes aligned and stacked neatly as in the picture?


enter image description here


Right now I have them in a row of 9 checkboxes but they're not aligned and are spaced according to the length of the text.


As seen here: JSFiddle


HTML:



<div class="tags">
<div class="col">
<label>
<input type="checkbox" rel="accounting" />Accounting</label>
<label>
<input type="checkbox" rel="courier" />Courier</label>
<label>
<input type="checkbox" rel="project-management" />Project Management</label>
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
<label>
<input type="checkbox" rel="video-games" />Dentistry</label>
<label>
<input type="checkbox" rel="video-games" />Librarian</label>
<label>
<input type="checkbox" rel="video-games" />Programmer</label>
<label>
<input type="checkbox" rel="video-games" />Architect</label>
</div>
<div class="col">
<label>
<input type="checkbox" rel="video-games" />Photographer</label>
<label>
<input type="checkbox" rel="video-games" />IT</label>
<label>
<input type="checkbox" rel="video-games" />Artist</label>
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
</div>
<div class="col">
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
<label>
<input type="checkbox" rel="video-games" />Forestry</label>
</div>
</div>
<!-- end tags -->


CSS:



.filter {
width: 850px;
padding: 25px;
border: 1px solid black;
margin: 25px;

.col {
width: 800px;
/* set to whatever width works for you */
/*float: left; */
/* put the columns next to each other */
}




Pre-Checked Checkbox function

we have on our orderform a function that allows to hide the order-button, when a user does not agree to the Terms and Conditions.


You can see it here: https://secure.purevisionmethod.com/orderforms/launch/step2.php


Right now the page comes up with the checkbox unchecked. We want to set it up, so that it's pre-checked, and that the order-button turns hiding, when a user unchecks the box.


I added checked="checked" to the of the checkbox, but the function controlling the show-hide function doesn't see it.


This is the function:



<script>
$('#agree_box').change(function(){
(this.checked)?$('#offer_fade').css('display','none'):$('#offer_fade').css('display','block');
});
</script>


Can you see why it's not recognizing the preselected checked="checked" within this piece of java?


Thanks!!





How can I pass the value and corresponding name of a checkbox when checked using javascript in ASP.NET?

I'm very new to ajax/javascript so I will try my best to explain my problem. Here's what I have so far:



$(function () {

$("#chkFilter").on("click", "input", function (e)
{
var filterCheckboxes = new Array();
$("#chkFilter").find("input:checked").each(function () {
//console.log($(this).val()); //works fine
filterCheckboxes.push($(this).val());
console.log($(this).val());

//var filterCheckboxes = new Array();
//for (var i = 0; i < e.length; i++) {
// if (e[i].checked)
// filterCheckboxes.push(e[i].value);
//}
});
console.log("calling ajax");
$.ajax({
url: "/tools/oppy/Default.aspx",
type: "post",
dataType: "json",
data: { UpdateQuery: filterCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});


Every time a checkbox is checked, ajax passes the data onto the server. Here is an example of some checkbox values after a few have been checked in the data form obtained from the Developer's Console:



UpdateQuery%5B%5D=sustrana%3AConditionalQuickWin&UpdateQuery%5B%5D=sustrana%3AQuickWin&UpdateQuery%5B%5D=http%3A%2F%2Fsustrana.com%2Fsustainability%23Environmental



sustrana:ConditionalQuickWin, Sustrana:QuickWin, http://sustrana.com/sustainability#Environmental etc. are the values of the checkboxes. Here, three checkboxes are checked.


But, I also want the name of the checkbox passed, as some checkboxes share the same name like so in this example URL:



tag=http://sustrana.com/sustainability#water&tag=...environment&speed=sustrana:quickwin



Where I can then parse this URL on the server and separate the values that are considered tags and values considered speed. Any and all resources related to this will be extremely appreciated, thank you. Please pardon any misconceptions I have about JS and ajax.





Thymeleaf + Spring Checkboxes not binding

Here's my snippets of code:


Vehicle Class:



// Duplicates
private Boolean regCard = true;
private Boolean decal;
private Boolean title;

public Boolean getRegCard() {
return regCard;
}

public void setRegCard(Boolean regCard) {
this.regCard = regCard;
}

public Boolean getDecal() {
return decal;
}

public void setDecal(Boolean decal) {
this.decal = decal;
}

public Boolean getTitle() {
return title;
}

public void setTitle(Boolean title) {
this.title = title;
}


Thymeleaf:



<form method="post" th:action="${flowExecutionUrl}" th:object="${customerModel.vehicle}">
<div class="duplicates">
<ul>
<li><label>What do you need to duplicate?</label>
<div class="regTitle">
<label>Registration Card
<input type="checkbox" th:field="*{regCard}"/>
</label>
<label>Decal
<input type="checkbox" th:field="*{decal}"/>
</label>
<div th:switch="*{vehicleType}">
<div th:case="'BR'">
<label>Title
<input th:type="checkbox" th:field="*{title}"/>
</label>
</div>
</div>
</div>
</li>
</ul>
<div class="clear"></div>
</div>
<div class="btm-btn-row">
<div class="btm-btn-left">
<a th:href="@{'~' + ${flowExecutionUrl}(_eventId='back')}">back</a>
</div>
<div class="btm-btn-right">
<input type="submit" value="continue" name="_eventId_continue" />
</div>
</div>
</form>


Generated HTML:



<form method="post" action="/IllinoisRVSWeb/main-flow?execution=e1s4">
<div class="duplicates">
<ul>
<li><label>What do you need to duplicate?</label>
<div class="regTitle">
<label>Registration Card
<input type="checkbox" id="vehicle.regCard1" name="vehicle.regCard" value="true" checked="checked" /><input type="hidden" name="_vehicle.regCard" value="on" />
</label>
<label>Decal
<input type="checkbox" id="vehicle.decal1" name="vehicle.decal" value="true" /><input type="hidden" name="_vehicle.decal" value="on" />
</label>
<div>
<div>
<label>Title
<input type="checkbox" id="vehicle.title1" name="vehicle.title" value="true" /><input type="hidden" name="_vehicle.title" value="on" />
</label>
</div>
</div>
</div>
</li>
</ul>
<div class="clear"></div>
</div>
<div class="btm-btn-row">
<div class="btm-btn-left">
<a href="/IllinoisRVSWeb/main-flow?execution=e1s4&amp;_eventId=back">back</a>
</div>
<div class="btm-btn-right">
<input type="submit" value="continue" name="_eventId_continue" />
</div>
</div>
</form>


Problem:


The boolean values never get set upon submit. I've tried the other way. Using a List object and binding that variable to the checkboxes with the proper th:value="'SOMETEXT'" for each checkbox. But that object stays null as well.


As you see I set one value to true beforehand to see if it would show up on the html side. It was successful. so its at least retrieving the value, but its not setting it if its ever changed.


Also, as you can see, I tried using "th:value="checkbox"" to see if that helped. It did not.


Thymeleaf Version 2.1.4


Spring 4.1.4


Spring WebFlow 2.4.0


Any help or tips would be great.


Thanks





Preventing a checkbox Checked event

I have a checkbox which on checking it I want to ask the user if he is sure and if not I will cancel the operation.

I tried the Click event but it turnes out it is only beeing called after the CheckedChanged event.

I thought I could at least do it "ugly" by asking the user inside the CheckedChanged event but then if he wishes to cancel I need to change the Checked value what raises the event all over again.

Another thing I would preferd to avoid with this solution is that even before the user replies the 'V' appears in the checkbox. I'm looking for an event that happens before the CheckedChanged and if such an event exists a way to prevent the CheckedChanged event.

Any other idea would be great as well of course.





Jquery - Select Manipulating with Checkboxes

I got a problem with my Script. Its working great with a "normal" name for the Selection, but I use a Shop CMS which names the Selection like this: "ItemOrderParams[0][g19]" and the script isnt working anymore with that name. Can somebody solve this problem? I have no Idea how to fix it.



$("input[id=steckdose]").on("change", function(){
if($(this).is(":not(:checked)"))
$(function() {
$('[name=ItemOrderParams[0][g19]]').val( '3' );
})
});
$("input[id=steckdose]").on("change", function(){
if($(this).is(":checked"))
$(function() {
$('[name=ItemOrderParams[0][g19]]').val( '2' );
})
});

<select name="ItemOrderParams[0][g19]">
<option value="1">Red</option>
<option value="2" selected="1">Green</option>
<option value="3">Blue</option>
</select>




updating an array after boxes are checked in java

i am really stuck. I want to update the projects and researchers array so that next time they are added to each others list is checked. Here is what ive done so far for this class. Any help would be appreciated, Thank you


code:



package view;


//all the imports are here



public class selectTeamMembers extends JFrame implements ActionListener, ItemListener{
ArrayList<Researchers> all;
ArrayList<Researchers> local;

ArrayList<Researchers> localselected;
int UREPcheck_count=-1;
int NPRPcheck_count=-1;
int type=0;//type=1 is UREP,type=2 is NPRP
Project pro;


JButton b1=new JButton("Add");
JButton b2=new JButton("Clear");
JButton b3=new JButton("Exit");
JPanel p1=new JPanel();

public selectTeamMembers(Arrays arr,Project pro){

super("selecting team members");
all=arr.getAllResearchers();
this.pro=pro;
if(pro instanceof UREP){
type=1;
JLabel label1=new JLabel("select the researchers that are on the team of this UREP project:");
Box box=Box.createVerticalBox();
box.add(label1);
for(int i=0;i<all.size();i++){
if(all.get(i) instanceof Faculty ||all.get(i) instanceof UnderGraduate){
JCheckBox b1=new JCheckBox(all.get(i).getName());
//checkboxes.add(b1);
box.add(b1);
//local.add(all.get(i));

b1.addItemListener(this);

UREPcheck_count=UREPcheck_count+1;


}//end if

} //end for
add(box,BorderLayout.CENTER);

} //end if urep


else if (pro instanceof NPRP){
type=2;
JLabel label1=new JLabel("select the researchers that are on the team of this NPRP project:");
Box box=Box.createVerticalBox();
box.add(label1);
for(int i=0;i<all.size();i++){
if(all.get(i) instanceof Faculty ||all.get(i) instanceof PostDoc||all.get(i) instanceof RA){
JCheckBox b1=new JCheckBox(all.get(i).getName());
box.add(b1);
//b1.addItemListener(this);
local.add(all.get(i));
NPRPcheck_count=NPRPcheck_count+1;

}

}

add(box,BorderLayout.CENTER);



}

p1.add(b1);
p1.add(b2);
p1.add(b3);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

add(p1,BorderLayout.SOUTH);
setSize(200,200);
setVisible(true);

}

@Override
public void actionPerformed(ActionEvent arg0) {

if(arg0.getSource()==b1){ //add



}


else if(arg0.getSource()==b2){ //clear



}

else if(arg0.getSource()==b3){ //exit
System.exit(0);

}


}

@Override
public void itemStateChanged(ItemEvent e) {
JOptionPane.showMessageDialog(null, "checked");

}


}




Getting Checkbox value in JavaScript or JQuery While OnClick

I had a Checkbox I need to get the value of checkbox of while checked. either in JavaScript or jquery. I have placed my ASPX Code below. that Should Work in IE, While I am trying it is Showing response as "on" rather than value.


ASPX code:



<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="CHK_STY_ALL" runat="server" onclick="javascript:Selectallcheckbox(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CHK_STY" runat="server" onclick="javascript:SelectallColorsForStyle(this,value);" CssClass="checkboxselection" Text='<%#Eval("STY_NBR")%>' />
</ItemTemplate>
</asp:TemplateField>


JavaScript and JQuery :



<script language="javascript" type="text/javascript">
function Selectallcheckbox(val) {
if (!$(this).is(':checked')) {
$('input:checkbox').prop('checked', val.checked);
} else {
$("#chkroot").removeAttr('checked');
}
}
</script>
<script type="text/javascript">
function SelectallColorsForStyle(e,val) {
var IDValue = $(e).attr('id');

var StyleNumber = document.getElementById(IDValue).value;
alert(StyleNumber);
}
</script>


enter image description here


Showing value as "ON" rather than the original value displaying aside of checkbox.





React checkbox onChange event not triggered

I am trying to change the state of a checkbox:



var React = require('react');

var UserTable = React.createClass({

handleCheckboxChange: function(field) {
return function(e) {
var value = !e.target.checked;
// this updates the state in the parent module
this.props.onUserUpdate(field, value);
// this persists the state to the server
this.props.onUserSave(field);
}.bind(this);
},


render: function() {
var user = this.props.data;
return (
<div className="ui toggle checkbox">
<input type="checkbox" onChange={this.handleCheckboxChange("topup_enabled")} checked={user.topup_enabled} />
<label></label>
</div>
);
}

});


Debugging this, I see that handleCheckboxChange is never being called.


Any idea why ?





HTML single Checkbox: Best practise whether to use value attribute or not

today i had a discussion with my colleague. The question was whether to use the additonal value attribute for a single HTML checkbox or not.


My preffered way is using a single checkbox without a additional value attribute and in backend doing a check like if



if (request.getParameter(checkboxName) != null)) {
...
}


My colleague argues that is would be more transparent using a single checkbox with a additonal checkbox value attribute like value="true" and doing a backend check like



if (Boolean.valueOf(request.getParameter(checkboxName))) {
...
}


As we want to make a small convention about our internal checkbox handling im now trying to find a "best practise" but couldn't find yet. I saw so far only examples with multiple checkbox with the same name. In this case of course it makes sense for me to use different values.


For me it seems to be a bit overhead using a value attribute in case of a single checkbox since i get always a String with "on" if its activated/checked.


We are using a Java Servlet/JSP MVC environment and im not 100% sure if this "on" comes from ServletRequest.getParameter.





Jquery if checkbox checked doesn't work?

Im trying to make a selection with progress bar for each checkbox when user checked one of the checkbox, the progress bar will show/display. So bar I already coded the css of progress bar is display:none; and also set if checkbox if checked $('.pbar').css('display','block'); , but this doesn't work , anyone can help me check my code please ? what mistake I have made . Thanks


JS Fiddle


HTML



<div id="popupfoot">
<p id="survey_title"></p>
<h5 id="choose"></h5>

<div id="survey_question"></div>
</div>


JS



var PG = {
divid: "",
multiselection: "",
optionitem: [],
init: function (divid, multiselection, optionitem) {
PG.divid = divid;
PG.multiselect = multiselection;
PG.optionitem = optionitem;

},
test: function () {
for (var i = 0; PG.optionitem.length > i; i++) {
alert(PG.optionitem[i].name);
}
},

render_1: function () {
$.each(array, function (i, obj) {

var selection = "<input class='the_checkbox' type='checkbox' id=" + obj.value + " name=" + obj.name + " value=" + obj.value + ">" +
"<label class='label' for=" + obj.value + ">" + obj.value + "</label>" +
"<div class='pbar'><div class='pbarinner' style='width:75%;'></div></div>";

$("#" + PG.divid).append(selection);
if ($('input#'+obj.value).is(':checked')) {
$('.pbar').css('display','block');
}


});



$("#survey_title").append("What is your favorite fruit??");
$("#choose").append("Please select 1 fruit only:");

$('.the_checkbox').on('change', function (evt) {
if ($(this).siblings(':checked').length >= PG.multiselect) {
this.checked = false;
}
});



},
render_2: function () {
$.each(w_array, function (i, obj) {
var selection = "<input class='the_checkbox' type='checkbox' id=" + obj.value + " name=" + obj.name + " value=" + obj.value + ">" +
"<label class='label' for=" + obj.value + ">" + obj.value + "</label>";


$("#" + PG.divid).append(selection);

});

$("#survey_title").append("item??");
$("#choose").append("Please select 3 item :");

$('.the_checkbox').on('change', function (evt) {
if ($(this).siblings(':checked').length >= PG.multiselect) {
this.checked = false;
}
});



},
save: function () {}
}


var array = [];
array[0] = {
"name": "fruit",
"value": "mango"
};
array[1] = {
"name": "fruit",
"value": "apple"
};
array[2] = {
"name": "fruit",
"value": "orange"
};
array[3] = {
"name": "fruit",
"value": "banana"
};


var w_array = [];
w_array[0] = {
"name": "com",
"value": "RAM"
};
w_array[1] = {
"name": "com",
"value": "DISK"
};
w_array[2] = {
"name": "com",
"value": "BOOK"
};
w_array[3] = {
"name": "com",
"value": "PEN"
};


PG.init("popupfoot", "1", array);
PG.render_1();
/*PG.init("survey_question", "3", w_array);
PG.render_2();*/




lundi 29 décembre 2014

Using checkboxlist to update registry?

I have a check list box that has 5 directories that my program will call later. I want the user to be able to check what directories they want to use with a checklistbox. So far they can chose each item they want and it will be added but i want unchecked boxs to be removed from the registry



private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
foreach (object checkbox in checkedListBox1.CheckedItems)
{
textBox1.AppendText("Item is marked: " + checkbox.ToString() + "\n");
RegBUP.SetValue(checkbox);
}
}




Gridview with paging enabled and checkBox, save items to database

I have a Gridview with paging enabled and checkBox, with Columns UserName, etc. On ButtonClick event I want to save the UserName to Database for selected checkbox. I am unable to get the UserName for the selected checkbox and stuck. Help appriciated.



protected void BtnSaveAuthorization_Click(object sender, EventArgs e)
{
}

protected void GVRegisterNewCarton_PageChanging(object sender, GridViewPageEventArgs e)
{

string pageId = string.Format("Page{0}", GVRegisterNewCarton.PageIndex);
bool[] selectedCheckboxes = new bool[GVRegisterNewCarton.PageSize];
for (int i = 0; i < GVRegisterNewCarton.Rows.Count; i++)
{
TableCell cell = GVRegisterNewCarton.Rows[i].Cells[0];
selectedCheckboxes[i] = (cell.FindControl("chkSelectAdd") as CheckBox).Checked;
}
ViewState[pageId] = selectedCheckboxes;
GVRegisterNewCarton.PageIndex = e.NewPageIndex;
BindData();


//Bind the gridview again



}

protected void GVRegisterNewCarton_PreRender(object sender, EventArgs e)

{
string pageId = string.Format("Page{0}", GVRegisterNewCarton.PageIndex);
bool[] selectedCheckboxes = ViewState[pageId] as bool[];
if (selectedCheckboxes != null)
{
for (int i = 0; i < GVRegisterNewCarton.Rows.Count; i++)
{
TableCell cell = GVRegisterNewCarton.Rows[i].Cells[0];
(cell.FindControl("chkSelectAdd") as CheckBox).Checked = selectedCheckboxes[i];
}
}
}




getting value of according to checked checkbox

I need to get value of according to checked checkbox... using HTML and JQuery or Javascript i have tried following code:


JQuey Code:



<script type="text/javascript">
$(function () {
$('input:not(#submit)').click(function () {
t = $(this).attr('id');

text = $('.time' + t).text();
//alert(text);
});

$('#submit').click(function (e) {
e.preventDefault();
var trs = $('table tr');
var values = trs.first().find('td');

var values1 = $('table tr td :checkbox:checked').map(function () {
return $(this).closest('tr').find('td').text() + "==>"
+ values.eq($(this).parent().index()).text();
}).get();

alert(values1);

});
});
</script>


HTML Code:



<body>
<table border="1">
<tr>
<td>No</td>
<td >Name</td>
<td >City</td>
<td >Check</td>

</tr>
<tr>
<td>1</td>
<td>
select</td>
<td>
select</td>
<td>
<input type="checkbox" name="checkbox" class="r1" />select</td>
</tr>
<tr>
<td>2</td>
<td>
select</td>
<td>
select</td>
<td>
<input type="checkbox" name="checkbox" class="r1" />select</td>

</tr>
<tr>
<td>3</td>
<td>
select</td>
<td>
select</td>
<td>
<input type="checkbox" name="checkbox" class="r1" />select</td>

</tr>
<tr>
<td>4</td>
<td>
select</td>
<td>
select</td>
<td>
<input type="checkbox" name="checkbox" class="r1" />select</td>

</tr>
</table>
<input type="submit" name="submit" id="submit" value="Save time sheet" />

</body>


I need to get value of of any row which checkbox is checked and i require multiple values also if multiple checkboxes are checked...





select and create checkbox list in php itself

I have written php code to generate dynamic checkbox list.I want to accept that checkbox checked value and use it furthur to display another checkbox list in php itself.


//Here's the code...



if($db_select=mysqli_select_db($conn,$db_value)) {
echo "selected database ".$db_value."\n";
}
echo "<br>";

echo "\n"." Select Tables : ";

$table="show tables from $db_value";
$result=mysqli_query($conn,$table);
while($row=mysqli_fetch_array($result)){
echo "<br>";
echo "<input type='checkbox' name='checklist[]' value='{$row[0]}'>{$row[0]}</input>";
}
echo "<br>";
echo "<input type='submit' value='validate' name='ok'>";
?>


I want to accept name='ok' and print another checkbox using php. How can I do it?





Marking off checkboxes in a table that match a specific text

I have a table (screenshot below) where I want to mark off the checkboxes that have the text "Xatu Auto Test" in the same row using selenium python.


http://i.imgur.com/31eDDkl.png


I've tried following these two posts:



But I couldn't get those solutions to work on my code.


My code:



form = self.browser.find_element_by_id("quotes-form")

try:
rows = form.find_elements_by_tag_name("tr")
for row in rows:
columns = row.find_elements_by_tag_name("td")
for column in columns:
if column.text == self.group_name:
column.find_element_by_name("quote_id").click()
except NoSuchElementException:
pass


The checkboxes are never clicked and I am wondering what I am doing wrong.


This is the HTML when I inspect with FirePath:



<form id="quotes-form" action="/admin/quote/delete_multiple" method="post" name="quotesForm">
<table class="table table-striped table-shadow">
<thead>
<tbody id="quote-rows">
<tr>
<tr>
<td class="document-column">
<td>47</td>
<td class="nobr">
<td class="nobr">
<td class="nobr">
<td class="nobr">
<a title="Xatu Auto Test Data: No" href="http://192.168.56.10:5001/admin/quote/47/">Xatu Auto Test</a>
</td>
<td>$100,000</td>
<td style="text-align: right;">1,000</td>
<td class="nobr">Processing...</td>
<td class="nobr">192.168....</td>
<td/>
<td>
<input type="checkbox" value="47" name="quote_id"/>
</td>
</tr>
<tr>
</tbody>
<tbody id="quote-rows-footer">
</table>
<div class="btn-toolbar" style="text-align:center; width:100%;">




Matching ranges with a checkbox

I think this is simple but I'm new to VBA. I have a row that I would like to be either 0 or a value from a different row (matching length and position). I have a computed financial statement line that I would like to bring into a different financial statement or null depending on a checkbox. Here is what I have so far but it just returns E111 for the entire range, I would like E60=E111, F60=F111, etc.


Private Sub CheckBox2_Click() With Worksheets("Project Model").Range("E60:KX60") If CheckBox2.Value = True Then .Value = 0 `If CheckBox2.Value = False Then .Value = ("E111) End With End Sub


Anyone know a quick fix?


Thanks!!





Adding multiple checkbox values to multiple columns in a single row

i read other threads but don't think i have found the answer (or maybe just don't know how to implement it...) for this. i have a mysql table with columns for an item size, amongst other things. the user fills in a form in which mulitple sizes may be selected from a series of checkboxes. i want to be able to insert the selected checkbox values in to the proper columns while leaving the other columns either null or if necessary i guess as a 0 value. the columns are tinyint format right now.


'One Size'



<input type="checkbox" name="itemSize[]" value="1" />


Small



<input type="checkbox" name="itemSize[]" value="2" />


Medium



<input type="checkbox" name="itemSize[]" value="3" />


Large



<input type="checkbox" name="itemSize[]" value="4" />


the database table has columns named oneSize, small, medium and large.




HERE IS THE CODE I USED TO TRY TO INSERT A RECORD BASED ON AN ARTICLE IN FOUND IN THE FORUM:



$itemName=$_POST["itemName"];
$allsizes=$_POST["itemSize"];
var_dump($allsizes);
$itemSizing="";
foreach($allsizes as $size){
$itemSizing .=$size .",";
}
$itemSizing=substr($allsizes, 0, -2);
$price=$_POST["price"];
$smallPrice=$_POST["smallPrice"];
$mediumPrice=$_POST["mediumPrice"];
$largePrice=$_POST["largePrice"];
$decsription=$_POST["description"];
$category_id=$_POST["category_id"];


and then in the insert statement i tried listing each column and then the values for the 4 item sizes taken from the checkboxes are listed as the concatenated string:



$SQL="INSERT INTO menuItems (itemName,oneSize,small,medium, large,price,smallPrice,mediumPrice,largePrice,description,category_id) VALUES ('$itemName','$itemSizing','$price','$smallPrice','$mediumPrice','$largePrice','$description','$category_id')";


THIS IS THE ERROR MESSAGE I GOT WHEN ATTEMPTING TO INSERT A RECORD FEATURING A SMALL SIZE AND A LARGE SIZE CHECKED OFF AND THE OTHER TWO CHECKBOXES LEFT UNCHECKED:


array(2) { [0]=> string(1) "2" [1]=> string(1) "4" } Warning: substr() expects parameter 1 to be string, array given in menuItems.php on line 162 INSERT INTO menuItems (itemName,oneSize,small,medium,large,price,smallPrice,mediumPrice,largePrice,description,category_id) VALUES ('Garden Salad','','','3.99','','6.99','Fresh greens with lettuce, tomatoes and cucumbers. Served with your choice of dressing.','3') : Error in query. Contact Site Admin




i thought that the string being created was a series of the checkbox values separated out for insertion into the various columns - which is exactly what i want to happen - but clearly it didn't work. i am obviously not very familiar with arrays so i apologize if this is a simple question.


thanks very much for any help anyone can provide...





How to manually group Radio Buttons Rails 4

I have 2 radio button in line for each table row. I need for them to work in a way that on 1 button in each row that can be clicked. Here's code where only one per column can only be selected due to rails automatically grouping them if they have same name attribute



...<tbody>
<% users_in_group(params[:group_id], params[:event]).each do |user| %>
<tr>
<td><%= user.fname + " "+user.lname %></td>
<td>fill</td>
<td>fill</td>
<td><%= radio_button_tag 'project[absent_user_ids][]', user.id, false %></td>
<td><%= radio_button_tag 'project[tardy_user_ids][]', user.id, false %></td>
</tr>
<%end%>
</tbody>...


Problem here is that I DO NOT want to change name parameter due to me having to re-implement the controller all over again... I will take answers if you can help me make check boxes behave in similar way.





How to find whcih checkboxes are selected and pass them to ActionResult in MVC?

I have a MVC5 app, and in one of my views, I have something like that:



<div id="subcatsform" class="form-group" style="visibility:hidden;">
@Html.LabelFor(m => m.Subcategories, new { @class = "col-md-3 control-label" })
<div id="subcats" class="col-md-9">

</div>
</div>


Then, in my JavaScript part, I do something like this in order to populate my empty div.



$(function () {

$("#CategoryID").on("change", function () {
var selected_option = $("#CategoryID option").filter(":selected").text();
$("#subcats").empty();

if (selected_option != "Please select a category") {
$("#subcatsform").css("visibility", "visible");

$.ajax({
url: "/Home/GetSubcategories",
dataType: "json",
data: {
cid: $("#CategoryID").val(),
},
success: function (data) {
$.each(data, function (key, value) {
var checkbox = '<input type="checkbox" name="subcategory" value="' + value.id + '"> ' + value.value + '<br />';
$("#subcats").append(checkbox);
});
}
});
}
else
{
$("#subcatsform").css("visibility", "hidden");
}
});

});


So, I simply check with category is previously selected, and then accordingly list all the subcategories found inside that category, and create input with type checkbox for each one of them. This works all fine, I'm able to get the appropriate subcategories when I change my category, and it creates the checkboxes for me.


The problem is that, later I don't know how to find out which checkboxes are selected, when the user presses the submit button in my view's form.


My ActionResult is defined like this:



public async Task<ActionResult> RegisterBusiness(BusinessViewModel model)


And inside my BusinessViewModel, I have a property defined like this:



public virtual ICollection<Subcategory> Subcategories { get; set; }


Any idea, how can I get the all checked checkboxes, and get their value property?





Apache POI - XSSF - Dealing with checkboxes

I am working with an excel-file which contains some checkboxes.


Is it possible to somehow get the current state (checked or unchecked)?


I found a page, which describes exactly that, but it is not using XSSF, but HSSF: http://zswap.wordpress.com/2010/12/08/fetching-option-or-radio-button-worksheet-form-control-from-an-excel-file-using-poi/


How can I do that using XSSF?





How to pass list of values from jsp to controller using form tags binding based on checkbox selection

My Jsp page :



<form:form id="multiCheckBox" commandName="courseDto" method="post" action="register.do">
<c:forEach items="${courseDto.courseList}" var="course" varStatus="loop">
<tr>
<td ><form:checkbox path="selectedCheckBox" class="course_data" value="${course.course_name}" /></td>
<td><c:out value='${course.id}' /></td>
<td><c:out value='${course.course_name}' /></td>
<td><form:input type="text"
path="course[${loop.index}].enrollment_date"
class="date-picker" />
</td>
<td><c:out value='${course.enrollment_status}' /></td>

</tr>
</c:forEach>
</table></div></td>
</tr>
</table><br>
<input type="submit" value="Submit Data">


My Controller :


@RequestMapping(value="/register.do",method=RequestMethod.POST) public String getInputForm(HttpServletRequest httpServletRequest, @ModelAttribute("courseDto") Course courseDto) { System.out.println(courseDto.getCourse_name()+"nnn"+courseDto.getId());


}


I am getting null values when I try to submit this,Please helo me in resolving this issue. Thanks in advnace..!!!





dimanche 28 décembre 2014

Android:save the checkbox state and find the checkbox location

i want to save my checkbox state using save preference method so when i closed the application the checked items are still there, but the problem i encouter is that i cannot get the checkbox array location or checkbox index, please help me with these


heres my main activity program



package com.example.cameraapp;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class FinalChoice extends Activity implements OnItemClickListener{
CheckBox checkbox;
List<File> lst;
ListView listView;
ArrayAdapter<Model> adapter;
List<Model> list = new ArrayList<Model>();
Button save;
ContextWrapper context;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.listview1hold);

listView = (ListView) findViewById(R.id.listView1);
adapter = new CustomAdapter(this,getModel());
listView.setAdapter(adapter);
listView.setOnItemClickListener((android.widget.AdapterView.OnItemClickListener) this);
save=(Button)findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {



Toast.makeText(getApplicationContext(), "FUCKYOU", Toast.LENGTH_SHORT).show();



}
});

}


public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
TextView label = (TextView) v.getTag(R.id.songsTexView);
checkbox = (CheckBox) v.getTag(R.id.checkBox1);
Toast.makeText(v.getContext(), label.getText().toString()+" "+isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();
}

private String isCheckedOrNot(CheckBox checkbox) {
if(checkbox.isChecked())
return "is checked";
else
return "is not checked";
}
private List<Model> getModel() {

String mp3Directory = "/Music";
String directoryPath= Environment.getExternalStorageDirectory().getAbsolutePath()+mp3Directory;
lst = getMP3Files(directoryPath);

//print in LogCat the list of .mp3:
for(int a=0;a<lst.size();a++){
list.add(new Model(lst.get(a).getName()));

}
return list;

}

public List<File> getMP3Files(String directory) {
List<File> files = new ArrayList<File>();
File folder = new File(directory);
for (File file : folder.listFiles()) {
if (file.isFile()) {
if (file.getName().endsWith(".mp3") || file.getName().endsWith(".MP3")) {
files.add(file);
}
}
}
return files;
}
public void saveInSp(String key,boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
}




Display check box as checked when false

The default functionality of the check_box_tag is to show it checked for true value hence the attribute "inactive" below would display as checked on true.



f.check_box :inactive


How can one have the opposite behaviour, i.e. show the checkbox checked when the value is false ?





Opacity CheckBox(VisualStudio) don't work

There's no code problem, the debug doesn't have any problem but when I test, when I checked the checkbox the opacity doesn't change. Nothing happen. I'm using VisualStudio 2013 Express. Here's the code:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TP3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void textBox1_TextChanged(object sender, EventArgs e)
{

int carac = textBox1.Text.Length;
label2.Text = carac.ToString();

}

private void label2_Click(object sender, EventArgs e)
{




}

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
Form Form1;
Form1 = new Form1();
if(checkBox1.Checked == true)
{
Form1.Opacity = 1;
}


}
}
}




samedi 27 décembre 2014

SelectList checkbox

My application is MVC 5, trying to develop multiselect checkbox using the following:



public static Dictionary<int, string> AdditionalInfo = new Dictionary<int, string>()
{
{ 1, "Exercise" },
{ 2, "Diet" }
};

public static int MapAdditionalInfo (string value)
{
return (from v in AdditionalInfo
where v.Value == value
select v.Key).FirstOrDefault();
}

public static string MapAdditionalInfo (int? value)
{
return (from v in AdditionalInfo
where v.Key == value
select v.Value).FirstOrDefault();
}

public string AdditionalInfo
{
get { return MapAdditionalInfo(AdditionalInfoID); }
set { AdditionalInfoID = MapAdditionalInfo(value); }
}


In the View:



@foreach (SelectListItem item in (IEnumerable<SelectListItem>)ViewData["Info"] )
{
<label><input value="@item.Value" name="AdditionalInfoID" id="AdditionalInfoID" type='checkbox' checked="@item.Selected" class="checkbox-inline" /><span class='lbl padding-4'>@item.Value </span></label>
}


In the controller:



ViewData["Info"] = MyModel.AdditionalInfo;


I get the following error:



Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.Int32,System.String]' to type 'System.Collections.Generic.IEnumerable`1[System.Web.Mvc.SelectListItem]'.


Would appreciate your suggestions on how to solve this error or if there a example for a better way to develop a checkbox list.





Javascript / HTML: Once Checkbox is clicked on, form fields then become required?

Please bear with me, and I hope I am clear with my question. I don't understand javascript that well, but I am trying to perform a certain task with it. Here is my questions;


I am using a checkbox and it shows/hides fields upon clicking the checkbox. I would like to make my fields required to input information only when I click on the checkbox and the fields are showing. When the fields are hidden, and the checkbox is not clicked on, then those fields are not required to input information. How do I make this happen. This is the code that I am using;



<script type="text/javascript" language="JavaScript">
function HidePart(d) {
document.getElementById(d).style.display = "none";
}
function ShowPart(d) {
document.getElementById(d).style.display = "block";
}
function CheckboxChecked(b,d)
{
if(b) {
ShowPart(d);
}
else {
HidePart(d);
}
}
</script>


<input type="checkbox" name="Loan2" value="yes" onclick="CheckboxChecked(this.checked,'checkboxdiv2')"> Add New Loan


<div id="checkboxdiv2" style="display:none">
Form Fields for input information
</div>


If this helps, this is my website: https://www.slfpusa.org/testing-page/. When I click on "Add New Loan", it produces more fields that I would like to only be required once they are showing. I hope my question is clear, and I hope to get some help in tweaking this javascript code to function to the way I need it to function. Any help would be much appreciated!





Microsoft Excel :: Checkbox Macro

I want it so that when I check the box for item 1, text appears next to it. I've written a simple macro for that already. The issue is, that I want the text to disappear when the box is unchecked. I have it so that when you check the box the text appears. If you uncheck the box, the text does not disappear, and I want it to. So basically, all I want it to do is to have text appear when I check the box, and the text disappear when I uncheck it. How can I do this.



Sub CheckBox1_Click()
'
' CheckBox1_Click Macro
'

'
Range("E2").Select
ActiveCell.FormulaR1C1 = "Puppy Tears"
Range("E3").Select
ActiveCell.FormulaR1C1 = "Tuna"
Range("E4").Select
End Sub




check box validation before clicking proceed button


<a href="page.html" > <button type="button" id="proceed-button">Proceed </button></a>

<input type="checkbox" name="checkbox3" value="yes">
By checking the box, I certify that have read the above disclaimers and agree to the rules. </input>


I have a checkbox and a button which will take me to next page. But, before I press the button the check box has to be ticked. If not, a label has to be displayed below the check box saying "accept to rules first". Help? Also, it would be great if i can highlight the checkbox to red if i click proceed without checking the checkbox. Can use javascript/jquery.





Datatable "Select all" checkbox checks checkboxes only for few seconds

I'm having an issue with Datatable selecting all checkbox rows. At the top of my table i have a checkbox with the id "select all". Each row of my table has a checkbox which is by default not checked.


This is the code i use to check all row checkboxes:



$('#selectAll').change(function() {
if( $(this).is(':checked') ) {
$('.row-checkbox').prop('checked', true);
} else {
$('.row-checkbox').prop('checked', false);
}
});


My issue is: after clicking on the select all checkbox, the checkboxes of all rows get checked, but only for 2 seconds, and they go back to unchecked. And ofcourse i want to them to stay checked. (page is not being refreshed or anything).


Does anyone know this problem? And/or know how this weird issue can be fixed? Or could point me in the right direction?


Thank you very much!!





Set CheckBoxTableCell in FXML

I currently have a problem with setting a CheckBoxTableCell from the FXML. I tried to convert this code to FXML:



tableCol.setCellValueFactory(new PropertyValueFactory<Product, Boolean>("property"));
tableCol.setCellFactory(CheckBoxTableCell.forTableColumn(toStockCol));


where 'property' is just some attribute of the 'Product' Class (from type 'boolean'). This code works fine. I now try to set this in the FXML, like this:



<TableColumn text="Some Col">
<cellValueFactory><PropertyValueFactory property="property" /></cellValueFactory>
<cellFactory><CheckBoxTableCell editable="true" /></cellFactory>
</TableColumn>


This doesn't work, I get the following error (which is a FXML LoadExeption):



Caused by: java.lang.IllegalArgumentException: Unable to coerce CheckBoxTableCell@24d62d1e[styleClass=cell indexed-cell table-cell check-box-table-cell]'null' to interface javafx.util.Callback.
at com.sun.javafx.fxml.BeanAdapter.coerce(BeanAdapter.java:495)
at com.sun.javafx.fxml.BeanAdapter.put(BeanAdapter.java:258)
at com.sun.javafx.fxml.BeanAdapter.put(BeanAdapter.java:54)
at javafx.fxml.FXMLLoader$PropertyElement.set(FXMLLoader.java:1409)
at javafx.fxml.FXMLLoader$ValueElement.processEndElement(FXMLLoader.java:786)
at javafx.fxml.FXMLLoader.processEndElement(FXMLLoader.java:2827)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2536)
... 42 more


I can not figure out what I am doing wrong. Also, in my opinion there is little to none documentation about how to set a CheckBox in a TableView with FXML.


Note: I would like to set this from the FXML, because it seems to be the spot for this. I know this can be done with the FXML controller. Also, I am just curious.


Any help is greatly appreciated!





Html Checkbox with images

i am trying to create a website, to do this i need to create list of checkboxes with images. But at the same time i am calling javascript function. first i want to show an image, then check box then the text. But i could not do it. i don't want to show it , first checkbox then image. here is my code.



<li class="arrow" onclick="functionCall('Text1');">Text1
<ul class="sub" style="display:none;" id="Text1">
<li onclick="Call('Text2');" id="id_1"> <input type="hidden" id="tid_1" value="0">Text2
<li onclick="Call('Text3');" id="id_2"> <img src="m1.png"/><input type="hidden" id="tid_2" value="0">Text3
</ul> </li>




Retrieving checkbox value in a dataTable

I have a datatable in which one of the columns is a bool. I display the value as a check box as such:



{
"mData": "IsAssociated", "mRender": function (data, type, full ) {
if (data == "true")
{
return '<input type="checkbox" checked="checked" />';
}
else
{
return '<input type="checkbox" />';
}
}
}


This works perfectly fine and the column appears as a check box in the datatable with the appropriate value (checked if true, unchecked if false). The problem i am having is retrieving the value of the column. I am using the "created row" callback in order to execute some jquery code as such:



"createdRow": function ( row, data, index ) {
alert(data[0]); //this works and return the integer value stored in the 0 column.
alert(data[1]); //this works and return the string value stored in the 1 column.
alert(data[2]); //this is the boolean column and this does not work. I get an "undefined"
//in the popup box that appears.
}


I have tried using the (bool) cast but that does not work either. How can I retrieve the value of the checkbox? Thanks.





parameter is lost while looping with php

i still not understand, with this simple logic but still make me not get the parameters declared variable name $form then, the result of $form is



<input type="checkbox" id="ID_0">
<input type="checkbox" id="ID_0">
<input type="checkbox" id="ID_0">
<input type="checkbox" id="ID_0">


not as expected, like this



<input type="checkbox" id="ID_0">
<input type="checkbox" id="ID_1">
<input type="checkbox" id="ID_2">
<input type="checkbox" id="ID_3">


my simple code is like this



$data = array(); //contains example 9 data
$total_data = count($data);

$sql = "SELECT name from table";
$result = $_CONN->Execute($sql);
$total = $result->RecordCount();

if($total > 0){
for($i=0;$i<$total_data;$i++){
$dataID = "ID_".$i;
while (!$result->EOF){
$form .= '<input type="checkbox" id="'.$dataID.'" name="checkData[]" value="'.$result->fields["name"].'">'.$result->fields["name"];
$result->MoveNext();
}
}
}else{
echo "No data from Table";
}




vendredi 26 décembre 2014

Append URL with checked checkbox's value

I am in need of appending my url with the value of the checked checkbox, I'm able to see the right value for every option in the inspector tool.


What needs to be appended:



<a href="#/edit/"><div class="edit">Edit</div></a>


The checkbox:



<input type="checkbox" value="{{item.iid}}">


So the Edit link should be able to go to for example /edit/K1 once the item with the value K1 is checked.


I have no clue how to do this, I guess this could be done by JQuery?





check/uncheck all or some checkboxes with javascript or jquery? [duplicate]


This question already has an answer here:




I have a page where I have a form at the top of the page that a user can select certain cities to filter on. So far it looks like this:



<?php

$start=_GET['start'];
$end=_GET['end'];

if(empty($start)){
$start=date("Ym");
}
if(empty($end)){
$end=date("Ym");
}


$places=array();
if(!empty($_GET['cities'])){
foreach($_GET['cities'] as $loc){
array_push($places,$loc);
}
}else{
$places=('CHI','DET','LA','NYC','DAL','SPR','PHI','PITTS','HST','KMZ','SCR','BUF','ALB','UTI','DEC','QNC','SNF');
}

?>

//html
<form method='GET'>
START:<input type='text' name='start' value= '<?$start?>'>
END: <input type='text' name='end' value='<?$end?>'>
<input type='checkbox' name='cities[]' value='CHI' <?= (in_array('CHI', $places)) ? 'checked' : ''; ?> >CHICAGO
<input type='checkbox' name='cities[]' value='DET' <?= (in_array('DET', $places)) ? 'checked' : ''; ?> >DETROIT
<input type='checkbox' name='cities[]' value='LA' <?= (in_array('LA', $places)) ? 'checked' : ''; ?> >LOS ANGELES
<input type='checkbox' name='cities[]' value='NYC' <?= (in_array('NY', $places)) ? 'checked' : ''; ?> >NEW YORK
<input type='checkbox' name='cities[]' value='DALLAS' <?= (in_array('DAL', $places)) ? 'checked' : ''; ?> >DALLAS
<input type='checkbox' name='cities[]' value='SPR' <?= (in_array('SPR', $places)) ? 'checked' : ''; ?> >SPRINGFIELD
<input type='checkbox' name='cities[]' value='PHI' <?= (in_array('PHI', $places)) ? 'checked' : ''; ?> >PHILADELPHIA
......rest of the cities....
<input type='submit' value='Filter'>
</form>

<?
$SQL="SELECT NAME,
ID,
PHONE,
EMAIL,
EVENT,
LOCATION
FROM SHOPPERS
WHERE LOCATION IN ('".implode("', '", $places)."')
AND EVENT BETWEEN '{$start}' and '{$end}'
AND ID BETWEEN '25687' AND '28050'
";

//and then fetch array to print out results...
.....
?>


This works just fine now. As soon as the page loads, all the cities are checked and the user can check/uncheck whatever they want. However, now, I want to add some boxes/buttons right above the cities with the state names in them, so that if I just want to filter on cities in Illinois, I can click/unclick that and it would check/uncheck Chicago, Decatur and Quincy. I also want to put two new buttons, one to select all and one to clear all. So the two new buttons would look something like this:



<input type="button" class="check" value="Select All" />
<input type="button" class="check" value="Clear" />


Any help? Thank you





Show text without alert when no checkbox is cecked

I have this js, but is working just when i delete de "nothing" field, but is ugly in my site if not showme couse i have no checkbox cheked.


js:



setInterval(function(){
section[0].innerHTML = '';
for(var i = 0; i < checkbox.length; i++){
if(checkbox[i].checked){
section[0].innerHTML += checkbox[i].value;
} else {
section[0].innerHTML = 'nothing';
}
}
}, 10);


html



Checked checkbox: <b><section></section></b>


This js is woking fine, but i wanna add nothing field:



setInterval(function(){
section[0].innerHTML = '';
for(var i = 0; i < checkbox.length; i++){
if(checkbox[i].checked){
section[0].innerHTML += checkbox[i].value;
}
}
}, 10);




How to create yii2 inline checkbox list

I have described my problem on yii2 forum, but no one helped me, most likely because no one knows the answer.


Here is the short description here.


I would like to make this:



<label class="checkbox-inline"><input type="checkbox" value="ASD">Option 1</label>
<label class="checkbox-inline"><input type="checkbox" value="DSA">Option 2</label>
<label class="checkbox-inline"><input type="checkbox" value="REW">Option 3</label>


but with yii2 checkboxList Html helper.


This is my simplified array of checkbox values



<?= $form->field($model, 'country')->checkboxList(['FR'=>'France', 'DE'=>'Germany']) ?>


I need to insert the class="checkbox-inline" into the label tags of each checkbox generated by this yii2 helper method but I can not figure out how to do it.


I was following these guides: checkboxList and checkbox one ( I can't post more than 2 links because I am new here ) but they are not helpful to me, I just do not understand what I have to do. Everything I tried just failed.


Can someone help me please, I am trying for 3 days now ?





Issue saving gridview checkbox checked items from multiple pages while paging

I have an issue saving gridview checkbox checked items values while paging. I am unable to retrieve the value items for which checkbox is checked. Appriciate any help in this regard



protected void BtnSaveAuthorization_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
try {

string pageId = string.Format("Page{0}", GVRegisterNewCarton.PageIndex);
bool[] selectedCheckboxes = ViewState[pageId] as bool[];
if (selectedCheckboxes != null)
{
for (int i = 0; i < GVRegisterNewCarton.Rows.Count; i++)
{

string UserName = ((Label)GVRegisterNewCarton.Rows[i].FindControl("UserName")).Text;

string DeptCode = ((Label)GVRegisterNewCarton.Rows[i].FindControl("DeptCode")).Text;

const string SQLFilePermoutDelivery = "INSERT INTO Test1(UserName, DeptCode) VALUES(@UserName, @DeptCode)";

SqlCommand cmdFilePermoutDelivery = new SqlCommand(SQLFilePermoutDelivery, con1);
cmdFilePermoutDelivery.Parameters.Add("@UserName", SqlDbType.VarChar);
cmdFilePermoutDelivery.Parameters["@UserName"].Value = UserName;
cmdFilePermoutDelivery.Parameters.Add("@DeptCode", SqlDbType.VarChar);
cmdFilePermoutDelivery.Parameters["@DeptCode"].Value = DeptCode;
con1.Open();
cmdFilePermoutDelivery.ExecuteNonQuery();
con1.Close();


BindData();

}
}

ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Success');", true);

BindData();
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);

}


}





Jstl checking checkboxes

I'm working with JSTL, and I'm trying to select checkboxes with a forloop. The problem is it doesn't work, nothing is checked. I think the error is in the line:



<c:if test="${field== 'company.id' }">


I don't know how I can write a ${} inside another ${}.



<c:forEach var="company" items="${companies}" varStatus="counter">
<li><input id="${counter.count}" class="companies" type="checkbox" onchange="checkButton('button1','companies')" name="companies" value="<c:out value="${company.id}" />"

<c:forEach var="field" items="${companyId}">
<c:if test="${field== 'company.id' }">checked="checked"
</c:if>
</c:forEach>>

<label for="${counter.count}"><c:out value="${company.name}"/></label></li>
</c:forEach>


Can somebody tell me how to fix this, so the right checkboxes get checked?





Php update checkbox states in db

I am new in php, i have a question. How can I update checkbox states in db? checkboxes have same name. when click on update button it will update all row checkboxes stat in db. and checkboxes in db get true or false


html part



<div class='blocks-output'>
<form action='/admin/blocks' method='post'>
<input type='hidden' name='updated_block_index' value=''/>
<input type='hidden' name='updated_block_name' value=''/>
<table class='table table-hover table-striped table-bordered'>
<thead>
<tr class='text-uppercase'>
<td>#</td>
<td>selected</td>
<td>block index</td>
<td>block name</td>
<td>edit</td>
<td>delete</td>
</tr>
</thead>
<tbody>
<?php foreach ($blocksInfo as $row) { ?>
<tr>
<td>
<?php echo $row['id']; ?>
</td>
<td>
<input type="checkbox" name='id' value='<?php echo $row['id']; ?>' <?php if($row['selected'] == 1) echo 'checked'; ?> />
</td>
<td>
<p><?php echo $row['block_index']; ?></p>

<div class='form-group hidea'>
<input type='number' class='form-control' name='block_index' placeholder='Block index' value='<?php echo $row['block_index']; ?>'>
</div>
</td>
<td>
<p><?php echo $row['block_name']; ?></p>

<div class='form-group hidea'>
<input type='text' class='form-control' name='block_name' placeholder='Block name' value='<?php echo $row['block_name']; ?>'>
</div>
</td>
<td>
<a href='' class='edit-row btn btn-primary' role='button'>edit</a>
<button class='update-row btn btn-primary' name='update_row' value='<?php echo $row['id']; ?>'>update</button>
</td>
<td>
<button type='submit' class='btn btn-primary' name='delete_row' value='<?php echo $row['id']; ?>'>delete</button>
</td>
</tr>
<?php } ?>

<tr>
<td>
<input type='submit' class='btn btn-primary' name='clear_table' value='delete all'>
</td>
<td></td>
<td></td>
<td></td>
<td ></td>
<td>
<input type='submit' class='btn btn-primary' name='update_table' value='update'>
</td>
</tr>
</tbody>
</table>
</form>
</div>


enter image description here


thank you :)





jeudi 25 décembre 2014

Multi delete checkbox on button click does not work as required

I have a grdiview in which I have added the Multi-delete functionality. Please see the code for your reference:-



<script type="text/javascript">
function ValidateAll() {
var chkselectcount = 0;
var gridview = document.getElementById('<%= grdTeacherProfile.ClientID %>');
for (var i = 0; i < gridview.getElementsByTagName("input").length; i++) {
var node = gridview.getElementsByTagName("input")[i];

if (node != null && node.type == "checkbox" && node.checked) {
chkselectcount = chkselectcount + 1;
}
}
if (chkselectcount == 0) {
alert("Please select atleast One CheckBox");
return false;
}
else {
ConfirmationBox();
}
}
function ConfirmationBox() {
var result = confirm("Are you sure, you want to delete the Users ?");
if (result) {
return true;
}
else {
return false;
}
}
</script>


Also see the button html:-



<asp:Button ID="btnDelete" runat="server" CausesValidation="false" CssClass="btn btn-danger" Text="Delete" OnClick="btnDelete_Click" OnClientClick="javascript:return ValidateAll();" />


The issue is that, when I check the checkboxes and Click on delete button, it asks for confirmation. When I click on Cancel it still deletes the row from the Gridview as well as sql table.


What should I do for the proper working of this. ? Please suggest





button enable and disable when user clicked on checkbox

here is my fiddle link, i dont know how to perform checkbox check events to enable disable buttons.



http://ift.tt/1H1guMT

Here i disabled all the checkbox. and i want to do the following operations. If i click on group selector, it must enable " delete, email and pdf buttons" . if the user click on any single row, it must enable all the buttons.


please help me on this, it may be an existing question, but i couldnt find right solution to solve it.





keypress,keyup not working in jquery Mobile

I have textFields and Checkboxs.If any text Will be enter in TextField1 automatically Checkbox1 will be checked and If textWill be removed in textField1 automatically Checkbox will be uncheck.I got output in browser.But When i Check in mobile it's not working



$("#LEDList .quantity input").keypress(function(e) {

var qtyId =this.id;
qtyId =qtyId.substr(qtyId.length - 1);
var regex = new RegExp("^[0-9]");
if (this.value.length == 0 && e.which == 48 ){
return false;
}
else{
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
$( "#check"+qtyId).prop( "checked", true );
return true;
}


e.preventDefault();
return false;
}
});
$("#LEDList .quantity input").keyup(function(e) {
var qtyId =this.id;
var qtyId1 =qtyId.substr(qtyId.length - 1);

if(($("#"+qtyId).val()).length ==0){

$( "#check"+qtyId1).prop( "checked", false );

}
});
}


I am not understanding.this code this not working in my Mobile so Please tell me .What wrong in my code.Please guide me .





mercredi 24 décembre 2014

Gridview checkbox maintain state while paging gives error

I am having issue with my gridview



  1. It is giving me error while moving from one page to another

  2. It is not retaining checkbox state on paging


Getting error on KeepChecks


ERROR MESSAGE Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index ERROR MESSAGE


Below is the code...


Your help and assistance will be appriciated



public partial class AdminConsole : System.Web.UI.Page
{

SqlDataAdapter da;
DataSet ds = new DataSet();


SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
BindData();
}

}





private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;

}

private void BindData()
{
SqlCommand cmd = new SqlCommand("SELECT UserID, EmployeeID, UserName, Dept FROM vw_UserID_Dept", con);

try
{
da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();
da.Fill(ds);

con.Open();
cmd.ExecuteNonQuery();
con.Close();

//GVRegisterNewCarton.DataSource = ds;
//GVRegisterNewCarton.DataBind();

if (!object.Equals(ds.Tables[0], null))
{
if (ds.Tables[0].Rows.Count > 0)
{
GVRegisterNewCarton.DataSource = ds.Tables[0];
GVRegisterNewCarton.DataBind();
Session["MyTable"] = ds.Tables[0];
}
else
{
GVRegisterNewCarton.DataSource = null;
GVRegisterNewCarton.DataBind();
}
}
else
{
GVRegisterNewCarton.DataSource = null;
GVRegisterNewCarton.DataBind();
}
}
catch (Exception ex)
{

Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Error Binding Grid');", true);
lblStatus.Text = ex.Message;

}




}

protected void GVRegisterNewCarton_PageChanging(object sender, GridViewPageEventArgs e)
{
try
{
KeepChecks();
GVRegisterNewCarton.PageIndex = e.NewPageIndex;
BindData();
ApplyChecks();
}

catch (Exception ex)
{

Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Error Binding Grid');", true);
lblStatus.Text = ex.Message;

}

}




private void KeepChecks()
{
try
{
ArrayList chkList = new ArrayList();
int index = -1;
foreach (GridViewRow gvrow in GVRegisterNewCarton.Rows)
{
index = (int)GVRegisterNewCarton.DataKeys[gvrow.RowIndex].Value;
bool result = ((CheckBox)gvrow.FindControl("chkSelectAdd")).Checked;

if (Session["RemindChecks"] != null)
chkList = (ArrayList)Session["RemindChecks"];
if (result)
{
if (!chkList.Contains(index))
chkList.Add(index);
}
else
chkList.Remove(index);
}
if (chkList != null && chkList.Count > 0)
Session["RemindChecks"] = chkList;
}
catch (Exception ex)
{

Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Error Binding Grid');", true);
lblStatus.Text = ex.Message;

}
}


private void ApplyChecks()
{
try
{
ArrayList chkList = (ArrayList)Session["RemindChecks"];
if (chkList != null && chkList.Count > 0)
{
foreach (GridViewRow gvrow in GVRegisterNewCarton.Rows)
{
int index = (int)GVRegisterNewCarton.DataKeys[gvrow.RowIndex].Value;
if (chkList.Contains(index))
{
CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelectAdd");
myCheckBox.Checked = true;
}
}
}
}

catch (Exception ex)
{

Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Error Binding Grid');", true);
lblStatus.Text = ex.Message;

}
}