I don't really know how to word this question so I am sorry if this seems a bit ambiguous. I have a situation where I am generating a bunch of check boxes within a cfloop. Each checkbox has the same class name of check, but they represent a value within a database. Originally I was hoping that I can just check to see if the checked property exists using jQuery, but that doesn't work as I'd hoped. The issue it brings is that if there is one checkbox that is checked and if I check or uncheck a different checkbox the class still returns a true value which makes sense logically.
Here is the ColdFusion which sets the checked value and the loop which generates the html:
<cfloop>
<cfif ContainsSic.HasSiC EQ 1 >
<cfset CheckedResult = "checked=""checked""" >
<cfelse>
<cfset CheckedResult = "" >
</cfif>
<cfoutput>
<tr>
<td align="center">#Passed_CustomerName#</td>
<td align="center">#Passed_LotNumber#</td>
<td align="center">#Passed_SubLot#</td>
<td align="center">#Passed_CarbonAvg#</td>
<td align="center"><input type="button" onclick="location.href='';" value="Amend" /></td>
<td align="center"><input type="checkbox" onclick="ajax(#Passed_CustomerID#, #Passed_LotNumber#, #Passed_SubLot#)" #CheckedResult#/></td>
<td align="center">Red Tag Page</td>
</tr>
</cfoutput>
</cfloop>
And here is the jQuery which handles the ajax call and the checked value:
function ajax(CustomerID, LotNumber, SubLot) {
if ($("input:checkbox").is(":checked")) {
var Checked = true;
}
else {
var Checked = false;
}
var passed_data = {
method: 'UpdateHasSiC',
CustomerID : CustomerID,
LotNumber: LotNumber,
SubLot: SubLot,
Checked: Checked
}
console.log(passed_data);
$.ajax({
type: 'POST',
url: 'LecoXMLRead_Ajax.cfc',
data: passed_data,
dataType: 'JSON',
success: function(data) {
},
error: function(e){
}
})
}
The workflow behind this is when the page loads, it grabs values from a database which determines whether or not the checkbox should be selected. It writes the values given from the database into rows with its designated checked or unchecked checkbox. The user should then be able to alter the checkbox and when doing so, update the value within the database with a 1 or 0. 1 representing it was checked of course.
I hope this makes sense, I can provide clarification or whatever else is needed.
Thank you
You can add custom data attribute at checkbox and then used that attribute value to pick checkbox
<input type="checkbox" data-customerId="#Passed_CustomerID#" onclick="ajax(#Passed_CustomerID#, #Passed_LotNumber#, #Passed_SubLot#)" #CheckedResult#/>
In function you can use that customer id to identify that specific checkbox.
I am considering customer id as unique value.
function ajax(CustomerID, LotNumber, SubLot) {
if ( $('[data-customerId="'+CustomerID+'"]:checkbox').is(":checked")) {
var Checked = true;
}
else {
var Checked = false;
}
}
Get rid of the onclick action, and change your markup/js to:
HTML:
<input type="checkbox" data-customerid="#Passed_CustomerID#" data-lotnumber="#Passed_LotNumber#" data-sublot="#Passed_SubLot#" #CheckedResult# />
JS:
<script>
$(document).ready(function () {
$('input[type="checkbox"][data-customerid]').on('click', function(e) {
ajax($(this).data('customerid'), $(this).data('lotnumber'), $(this).data('sublot'), $(this).is(':checked'));
});
});
</script>
Then you would add the checked argument to your ajax function.
(I didn't test this, so look for syntax errors. LMK and I'll correct if found.)
Related
I've been searching for this for a couple hours with no luck. This seems like it should be fairly easy but I am obviously overlooking something.
I have a table, with each row displaying information in each cell. At the end of each of the rows, there is an additional cell with a checkbox in it. The checkbox is an array, and each checkbox value is an imploded array via PHP. See below:
HTML/PHP
--------
(...some html code...)
<form method="post" action="the-next-page.php">
<table>
<tr>
<?php
(...some php SQL query code...)
while ($row = oci_fetch_array($result)) {
?>
<td><input type="text">Name</td>
<td><input type="text">City</td>
<td><input type="checkbox" name="checkGroup[]" value="<?php implode(":",$someArrayvariable) ?>"></td>
<?php
}
?>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
....
</html>
Passing the imploded values to the next page works fine. No problem there.
I have been trying to create a javascript function to check all of the boxes that are in this form, or under the checkbox group's name, or whatever I can do to check them all with the click of a button. I've tried variations of the following with no success:
HTML (On the top of the same script as above)
----
<button name="checkAll" onclick="checkAll()">Check All</button>
Javascript (On the bottom of the same script as above)
----
<script type="text/javascript">
function checkAll() {
var checks = document.getElementByName("checkGroup");
for (var i=0; i < checks.length; i++) {
checks[i].checked = true;
}
}
</script>
I can't figure out what I'm doing wrong. I know that a variation of this question has been asked before many times, but I don't seem to be getting any results. I'm guessing because my checkboxes name is an array (checkGroup[] ???).
When I click the button to check all of the checkboxes in the form, nothing happens.
Any ideas? Thanks in advance.
-Anthony
You can use JQuery to make this easier on yourself.
I would also assign a general class name to each checkbox input, so then in Javascript (using JQuery):
$(".classname").each(function() {
$(this).prop("checked",true);
});
I would also give the Check All button a unique class/id so you can do this
$(document).ready(function() {
$("#allcheckboxid").on("click",function() {
$(".classname").each(function() {
$(this).prop("checked",true);
});
});
})
Two minor things:
function checkAll() {
var checks = document.getElementsByName("checkGroup[]");
for (var i=0; i < checks.length; i++) {
checks[i].checked = true;
}
}
getElementByName should be getElementsByName, and checkGroup should be checkGroup[]. Other than that your code should be good to go!
Try this way to get all checked check box elements
<button name="checkAll" onclick="checkAll()">Check All</button>
<script type="text/javascript">
function checkAll() {
var checkboxes = document.getElementsByName('checkGroup[]');
var checkboxesChecked = [];
for (var i=0; i<checkboxes.length; i++)
{
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
</script>
I have the following row in a table.
<tr class="data_rows" ng-repeat='d in t2'>
<td class="tds"> <input class='checkBoxInput' type='checkbox' onchange='keepCount(this)'></td>
<td class="tds"><a href='perf?id={{d.ID}}'>{{d.ID}}</a></td>
<td class="tds">{{d.HostOS}}</td>
<td class="tds">{{d.BuildID}}</td>
<td class="tds">{{d.Description}}</td>
<td class="tds">{{d.User}}</td>
<td class="tds">{{d.StartTime}}</td>
<td class="tds">{{d.UniqueMeasure}}</td>
<td class="tds">{{d.TotalMeasure}}</td>
</tr>
Here's the HTML for button that will invoke the function to collect the ids from checked check boxes and store them.
<div id='compButtonDiv' align='center' style="display: none;">
<input id='cButton' type='button' value='compare selections' onclick='submitSelection()' style= "margin :0 auto" disabled>
</div>
The data is in t2 which consists of an array of length 15-20.
What i want to do is get the value of ID i.e, {{d.ID}} of the 2 checked check boxes so that i can store them in a variable and pass them as query parameters to URL using `location.href = url?param1¶m2'
Here's the javascript:
function keepCount(obj){
debugger;
//var count=0;
if(obj.checked){
obj.classList.add("checked");
}else{
obj.classList.remove("checked");
}
var count = document.getElementsByClassName("checked").length;
var cBtn = document.getElementById('cButton');
//alert(count);
if(count == 2){
cBtn.disabled = false;
}
else if(count < 2){
cBtn.disabled= true;
}
else{
cBtn.disabled= true;
alert("Please Select two sets for comparison. You have selected: " + count);
}
}
function submitSelection(){
// what should be the code here??
location.href= "existingURL?a&b";
}
Now can someone please tell me how to get the id's?? I need to extract ID from the checkboxes that are checked(on the click of button whose code i've mentioned above'.
Thanks.
-Ely
Firstly when we use angularjs we tend to depend less and less on DOM manipulation.
For this reason, what you can do is to attach ngModel to the checkbox.
Like:
<input class='checkBoxInput' ng-model='d.isChecked' type='checkbox' onchange='keepCount(this)'>
What this does is, it attaches the variable (in your case the property of item in the list) to the check box. If it is checked it is true, if unchecked, initially it will be undefined, later on checking and then unchecking it will be false.
Now, when you submit, just loop over the original list in the function and check the values of d.isChecked (true/falsy values). Then you can add the necessary items in a separate list for submission.
The only concern is when checking the list on submission , check if(d.isChecked), so that it ignores the falsy values(false/undefined).
background
I have a table grid of checkboxes, grouped by name, and each checkbox contains a time value. An example of the HTML:
<td><input type="checkbox" name="tuesday[]" value="10am"></td>
<td><input type="checkbox" name="tuesday[]" value="11am"></td>
<td><input type="checkbox" name="tuesday[]" value="12pm"></td>
<td><input type="checkbox" name="tuesday[]" value="1pm"></td>
<td><input type="checkbox" name="tuesday[]" value="2pm"></td>
<td><input type="checkbox" name="tuesday[]" value="3pm"></td>
<td><input type="checkbox" name="tuesday[]" value="4pm"></td>
<td><input type="checkbox" name="tuesday[]" value="5pm"></td>
<td><input type="checkbox" name="tuesday[]" value="6pm"></td>
<td><input type="checkbox" name="tuesday[]" value="7pm"></td>
When the form is submitted, the values are POSTed how I want them to be; all the checked times are in the tuesday[] array.
problem
I want to do some client-side validation with jQuery. I want to check that at least one checkbox is checked.
I have tried storing it into a var like so:
var availTuesday = $("input:checkbox[name='tuesday']:checked");
But when I do so and the console.log(availTuesday);, nothing is shown (regardless on if something is checked or not). I have also tried console.log(availTuesday.serialize());
Question:
how can I retrieve the user-checked values for the tuesday[] checkbox group, as well as for the other dates (wednesday[], thursday[], etc)?
Thank you.
The selector is not correct, change it to:
var $tuesday = $("input[type=checkbox][name='tuesday[]']:checked");
For getting the values you can use .map() method which returns an array:
if ($tuesday.length) {
// Getting values of the checked checkboxes
var values = $tuesday.map(function(){
return this.value;
}).get();
// ...
} else {
// There is no checked `day[]` checkbox
}
In case that you have other similar set of checkboxes you can use an array:
var days = ['days', 'in', 'a', 'week'],
values = {},
errors = [],
$checkboxes = $("input[type=checkbox]");
$.each(days, function(_, day) {
var $set = $checkboxes.filter('[name="'+day+'[]"]:checked');
if ($set.length) {
values[day] = $set.map(function() {
return this.value;
}).get();
} else {
// There is no checked `day[]` checkbox
errors.push(day);
}
});
if (errors.length) {
// console.log('Please check at least one hour in ' + errors.join(', ') + ' days ...');
} else {
// console.log(values);
}
You can try
var availTuesday = [];
$('input[type=checkbox][name="tuesday[]"]:checked').each(function() {
availTuesday.push($(this).val());
});
JSFiddle
If you want the actual value
var values = $("input[type=checkbox][name='tuesday[]']:checked").map(function() {
return this.value;
}).get();
If all you are really after is if any boxes are selected you can do the following:
if($('input[type="checkbox"][name="tuesday[]"]:checked').length) {
...
} else {
...
}
The length value is a property of the jQuery object (superset of DOM object) that specifies how many nodes matched the selector. In this case, if you check the length and the value is 0, no :checked checkboxes with the name tuesday[] exist (i.e. the user has not checked any boxes so display your validation message). It's quick and dirty validation. If you're looking to retrieve the values, the multitude of other answers are probably better.
You'll need to fix the selector to match the name, as others have mentioned.
If you just want to test that one is checked, you can go straight to a boolean, like this:
var availTuesday = $("input:checkbox[name='tuesday[]']:checked").length > 0;
I have N number of radio button groups in the page with auto generated names.
I want to call a javascript function as the value of the checked property. THIS LINE EXCLUDED AFTER EDIT ( Depending on the return value, the radio button needs to be checked or unchecked.)
<input type="radio" name="auto_generated_name" value="some_value" checked="test_check(args);" />
and the javascript function is
function test_check(params) {
if(conditions){
return true;
}
else
return false;
}
But that does not work. Whatever value I assign to 'checked' property, be it any javascript function or any string etc, the radio button becomes checked.
How can I achieve my goal?
EDIT:
<input type="radio" name="auto_generated_name" value="somevalue" onclick="test_check(args)"/>
4 radio buttons make a group. such N radio groups have html class names in this way : button_group_1, button_group_2, button_group_3, button_group_4 etc.
The 'args' need to be these class (i.e. radio button group) names and the corresponding values (from value="1", value="2", value="3" and value="4" ).
Cookies with the class names and values will be created inside the javascript function.
On page refresh, cookies matching with the class names will be checked and depending on the existence of the corresponding cookies, the radio button will be checked or unchecked.
How to achieve the goals/
Assuming you are using jQuery, use the change event: http://api.jquery.com/change/
The checked attribute is simply a boolean value to indicate whether the radio button should be checked, it cannot contain script, or a reference to a scripting function. Any value in the attribute will cause the radio button to be checked.
Without knowing what mechanism you are using to check each radio button - I can see an args variable but don't know what type this is - it's going to be tricky to write some code for you.
If you can make args into an array of values, then something along the lines of the following should work for you:
var args = new Array(true,false,true)
$.each(args, function(index, value) {
$("INPUT[type=radio]").eq(index).attr("checked", value)
});
Here's a fiddle to show what I mean more clearly
check this output, valid args is 'aa'.
http://jsfiddle.net/X7rcC/1
html:
<input type="radio" name="auto_generated_name" value="some_value1" checked="bb" />
js:
$(function() {
var radios = $("input[type='radio']");
$.each(radios, function(index, value){
var args = value.attributes[1].nodeValue;
test_check(args, value);
})
});
function test_check(params, value){
if(params == "aa"){
$(value).attr("checked",true);
}else
$(value).attr("checked",false);
}
try this:
Here I user a custom attribute to input named groupname. In OP's case groupname="<?php echo $radio_button_group_name; ?>". Then checking the value of this attribute OP can assign checked attribute value.
<input type="radio" name="r1" groupname="gr1"/>
<input type="radio" name="r2" groupname="gr2"/>
$('input:radio').each(function() {
if ($(this).attr('groupname') == 'gr1') {
$(this).attr('checked', true);
} else {
$(this).attr('checked', false);
}
});
Your question really boils down to:
How can I set the value of a checkbox when the page first loads? (Using a parameter stored with the checkbox)
The key insights are:
you can't store a function inside a parameter and expect it to automatically evaluate on load
you can store the data about an object inside data- properties
you can set the value of objects on page load in jQuery using the $(document).ready() event
.
<script type="text/javascript">
$(document).ready( function() { // this code runs when the page is first loaded
var radios = $("input[type='radio']"); // find all of your radio buttons
$.each(radios, function(){
var radio = $(this);
var param = radio.attr('data-param'); // retrieve the param from the object
radio.attr('checked', test_check(param) ); // set the value of the radio button
})
});
function test_check(params) {
if(conditions){
return 'checked';
}
else
return '';
}
</script>
You cannot use a checked attribute this way, because anything as the value will be the same as checked=true Even just checked checks a radio button. What you should do is use a custom attribute which will create the checked attribute:
<input type="radio" name="auto_generated_name" value="some_value" needs_check="param">
<script>
// Do test_check on param for each input
$('input:radio').each(function()
{
var radio = $(this);
var param = radio.attr('needs_check');
var condition = test_check(param);
radio.attr('checked', condition);
});
function test_check(param)
{
return true or false based on param
}
</script>
I was facing same problem and my conclusion is that don't use " " to contain a function.
Correct:
<input type="radio" name="im" id="b1" onclick=alert("hello"); />
Incorrect:
<input type="radio" name="im" id="b1" onclick="alert("hello");" />
I have the following code to check a checkbox as soon as the user types something in the textbox. This works fine for a single text box.
function activateCheckbox() {
if (document.myForm.box1.checked == false) {
document.myForm.box1.checked = true;
}
}
<tr>
<td><input type="text" id="mySearch1" name="mySearch1" size="40" onkeypress="activateCheckbox()"/></td>
<td><input type="checkBox" id="box1" name="box1"/></td>
</tr>
However suppose there are more than one text boxes with a checkbox against each one and I want that only the corresponding checkbox should be checked. I modified the above code as shown below by passing a parameter to the function but it's not working, because "document.myForm.id.checked" doesn't work as it accepts the checkbox name instead of "id". Please suggest if there are better alternatives or how do I modify my code to make it working?
function activateCheckbox(id) {
if (document.myForm.id.checked == false) {
document.myForm.id.checked = true;
}
}
<tr>
<td><input type="text" id="mySearch1" name="mySearch1" size="40" onkeypress="activateCheckbox('box1')"/></td>
<td><input type="checkBox" id="box1" name="box1"/></td>
</tr>
<tr>
<td><input type="text" id="mySearch2" name="mySearch2" size="40" onkeypress="activateCheckbox('box2')"/></td>
<td><input type="checkBox" id="box2" name="box2"/></td>
</tr>
<tr>
<td><input type="text" id="mySearch3" name="mySearch3" size="40" onkeypress="activateCheckbox('box3')"/></td>
<td><input type="checkBox" id="box3" name="box3"/></td>
</tr>
You have a couple of options. You can do:
function activateCheckbox(id) {
if (document.myForm[id].checked == false) {
document.myForm[id].checked = true;
}
}
...or personally, I think this is a bit more clear:
function activateCheckbox(id) {
var checkbox = document.getElementById(id);
if (! checkbox.checked) {
checkbox.checked = true;
}
}
The first approach works because in JavaScript obj.someProperty means the same semantically as obj["someProperty"]. So if you have a variable that stores the name of the property you want to access, you can always do obj[name] to access the property.
The second approach is just finding the checkbox in the DOM by its id. It seems cleaner to me, since you are setting the id of each checkbox anyways and since you called your variable "id".
Also note that your if statement is superfluous. The checked attribute will only ever be true or false (you can subvert this by storing other things there, but that's a completely separate topic). So setting it to true whenever it is false is logically equivalent to always setting it to true, and you can implement your handler function with a single line, like:
function activateCheckbox(id) {
document.getElementById(id).checked = true;
}
.id means literally the id property. In case you want to have it set dynamically, use the [] notation:
function activateCheckbox(id) {
if (document.myForm[id].checked == false) {
document.myForm[id].checked = true;
}
}
['test'] means .test, ['abc'] means .abc. So [id] means: access the property that id has as its value.
I advise you to use a JQuery (www.jquery.com). By adding one code line
<script src="http://code.jquery.com/jquery-1.6.2.min.js" type="text/javascript"></script>
you can solve your problem problem by write just one code line:
$('#checkboxId').attr('checked','checked');
or you can check
$('input[type="checkbox"]').attr('checked','checked');
or unckeck
$('input[type="checkbox"]').attr('checked','');
all checkboxes in you document