Im trying to build a page that will allow a user to select a maximum of 8 out of 20 checkboxes, in a specific order, on a single form.
Im trying to make a page that will only be viewable if the right sequence of checkboxes are clicked, a neat way to let only those who have the checkbox sequence in on a certain part of my website.
What I need to know is, once they select the checkboxes, how can I not only pass it on to a test page to view the data, but also, how to pass the data showing the exact sequence of how the checkboxes were checked.
Example: The check boxes are numbered one from twenty. If they select checkbox1,checkbox4,checkbox2,checkbox7,etc, Id like the data to be passed on in the exact order checked, 1,4,2,7,etc
So far, I have have the form done, Id like to know what I need to add to the javascript in order to pass the variables on exactly as checked.
Here is the Javascript:
<script type="text/javascript">
<!--
//initial checkCount of zero
var checkCount=0
//maximum number of allowed checked boxes
var maxChecks=3
function setChecks(obj){
//increment/decrement checkCount
if(obj.checked){
checkCount=checkCount+1
}else{
checkCount=checkCount-1
}
//if they checked a 4th box, uncheck the box, then decrement checkcount and pop alert
if (checkCount>maxChecks){
obj.checked=false
checkCount=checkCount-1
alert('you may only choose up to '+maxChecks+' options')
}
}
//-->
</script>
<script type="text/javascript">
<!--
$(document).ready(function () {
var array = [];
$('input[name="checkbox"]').click(function () {
if ($(this).attr('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
}
}
}
// Clear all labels:
$("label").each(function (i, elem) {
$(elem).html("");
});
// Check the array and update labels.
for (var i = 0; i < array.length; i++) {
if (i == 0) {
$("#" + array[i].toUpperCase()).html("1");
}
if (i == 1) {
$("#" + array[i].toUpperCase()).html("2");
}
if (i == 2) {
$("#" + array[i].toUpperCase()).html("3");
}
if (i == 3) {
$("#" + array[i].toUpperCase()).html("4");
}
if (i == 4) {
$("#" + array[i].toUpperCase()).html("5");
}
if (i == 5) {
$("#" + array[i].toUpperCase()).html("6");
}
if (i == 6) {
$("#" + array[i].toUpperCase()).html("7");
}
if (i == 7) {
$("#" + array[i].toUpperCase()).html("8");
}
}
});
});
//-->
</script>
Here is an example of the input fields:
<td width="20" align="center" valign="middle"><label id="1"></label><input name="checkbox" type="checkbox" value="1" onclick="setChecks(this)"/></td>
<td width="20" align="center" valign="middle"><label id="2"></label><input name="checkbox" type="checkbox" value="2" onclick="setChecks(this)"/></td>
<td width="20" align="center" valign="middle"><label id="3"></label><input name="checkbox" type="checkbox" value="3" onclick="setChecks(this)"/></td>
<td width="20" align="center" valign="middle"><label id="4"></label><input name="checkbox" type="checkbox" value="4" onclick="setChecks(this)"/></td>
<td width="20" align="center" valign="middle"><label id="5"></label><input name="checkbox" type="checkbox" value="5" onclick="setChecks(this)"/></td>
and so on up to 20
I am a noobie, and I pieced together what I have so far, from various sources.
I am having trouble understanding how to grab the array data from the second snippet of javascript, and passing it along to a php page I need to create that will echo it in order to test to see if it is indeed passing along the variables in the exact order they were clicked.
Any help would be appreciated.
There is a very similar question here that asks for a way to detect the order of selected checkboxes.
Full code in jsFiddle
Select/Unselect the checkbox then click the textarea to see your array.
What I did there is simply add new element on the array when user select a checkbox. If he deselect it will find the index by its value and remove from the array.
Then you can check the length using arrayName.length, if it matches your condition then you can submit.
Just push the IDs of the checkboxes onto an Array, then convert that to a string and post it back. Array[0] will be the first, etc. If Array.length > 7, disable the other checkboxes that are not in the array. That should be simple enough.
Related
I am trying to select some radio button on a webpage using Javascript inside Tampermonkey. For this particular button, there is no element ID, so I'm not really sure how to select them.
There's really no other identifying elements for these buttons that I can see.
Note: There's several radio buttons on this page, and the only unique identifier between them is the "value." There are 12 other buttons, but I want these 3 selected by default after the page loads.
<input name="Offense" type="radio" value="Indifferent">
<input name="Likelihood" type="radio" value="Indifferent">
<input name="Humor" type="radio" value="Indifferent">
So, I tried to catch them all at once with this:
document.getElementByValue("Indifferent").checked = true;
but it's not doing anything, I'm sure I'm missing something.
Thank you!
Using querySelector/querySelectorAll from Selectors API returns a NodeList of matching DOM Nodes. Since it is not an Array, a for-loop is used:
var inputs = document.querySelectorAll('input[value="Indifferent"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
}
The same in jQuery:
$('input[value="Indifferent"]').attr('checked', true);
// list will contain all the radio buttons
var list = $('input[value="Indifferent"]')
$.each(list, function(index, value) {
alert( index + ": " + value );
});
All the data you need will be in the value object
https://jsfiddle.net/o46rhpwL/
And if you are looking for the checked value in the list
https://jsfiddle.net/z73ah82b/
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 am trying to make a page that allows users to select 8 checkboxes from a total of 25.
Im wondering, how to detect the exact order in which they check them. I am using a plain html front page that will be verified by a form action pointing to a php page.
Im trying to get a result like (checkbox1,checkbox2,checkbox6,checkbox3,checkbox7,etc) for eight checkboxes, and the exact order in which they were clicked.
I think I have found what I am looking for,Im not too sure, but Im having trouble implementing it.
This is what I have so far, I guess my question is, what type of php do I need to gather this info once a user has submitted the form.
For the form I have:
<form id="form1" name="form1" method="post" action="check_combination.php">
<label id="lblA1"></label>
<input name="checkbox1" type="checkbox" value="a1" onclick="setChecks(this)"/> Option 1
<label id="lblA2"></label>
<input name="checkbox1" type="checkbox" value="a2" onclick="setChecks(this)"/> Option 2
<label id="lblA3"></label>
<input name="checkbox1" type="checkbox" value="a3" onclick="setChecks(this)"/> Option 3
<label id="lblA4"></label>
<input name="checkbox1" type="checkbox" value="a4" onclick="setChecks(this)"/> Option 4
</form>
For the Javascript I have:
<script type="text/javascript">
<!--
//initial checkCount of zero
var checkCount=0
//maximum number of allowed checked boxes
var maxChecks=8
function setChecks(obj){
//increment/decrement checkCount
if(obj.checked){
checkCount=checkCount+1
}else{
checkCount=checkCount-1
}
//if they checked a 4th box, uncheck the box, then decrement checkcount and pop alert
if (checkCount>maxChecks){
obj.checked=false
checkCount=checkCount-1
alert('you may only choose up to '+maxChecks+' options')
}
}
//-->
</script>
<script type="text/javascript">
<!--
$(document).ready(function () {
var array = [];
$('input[name="checkbox1"]').click(function () {
if ($(this).attr('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
}
}
}
// Clear all labels:
$("label").each(function (i, elem) {
$(elem).html("");
});
// Check the array and update labels.
for (var i = 0; i < array.length; i++) {
if (i == 0) {
$("#lbl" + array[i].toUpperCase()).html("first");
}
if (i == 1) {
$("#lbl" + array[i].toUpperCase()).html("second");
}
}
});
});
//-->
</script>
I have gotten the part that only allows 8 checkboxes to be checked, but Im stuck as to what I need to do to actually parse the data once it has been submitted to a page with a name like check_combination.php.
I would appreciate any help
create a hidden input field with the order
update this input field when something changes
you'll have the order ready to be processed by PHP