My goal is If all checkbox are check the person can go further if not it will go to an excuse page.
I found this in jQuery:
$("input[type='checkbox'].itemCheck").change(function(){
var a = $("input[type='checkbox'].itemCheck");
if(a.length == a.filter(":checked").length){
console.log("Je vais sur la formulaire");
}
});
I tried it and it works but I need it in vanilla js so I tried to convert it but I just can't find out how to accomplish this.
I tried other logic to make it work but I can't figure how.
<input type="checkbox" name="verif" class="checkbox itemCheck">
<input type="checkbox" name="age" class="checkbox itemCheck">
<input type="checkbox" name="employed" class="checkbox itemCheck">
The vanilla JavaScript version of that jQuery code would be: (Added comments so you can understand what is happening)
// gets all the inputs on the page with type = "checkbox"
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
// loops through each checkbox
for (var i = 0; i < checkboxes.length; i++) {
// add an change event listener to each checkbox
checkboxes[i].addEventListener('change', function() {
// gets the checkboxes that are ticked (or "checked")
var checkboxes_ticked = document.querySelectorAll('input[type="checkbox"]:checked');
// check if the length of ticked checkboxes matches with the total checkboxes on the page
if (checkboxes_ticked.length === checkboxes.length) {
// all checkboxes where ticked! display your message
console.log("Je vais sur la formulaire");
}
});
}
Good luck.
Related
Basically, I create a checkbox range with pure JS. What I can't figure out, how to make checked range impossible to uncheck. For example you check 2 and 5. So number 3 and 4 should be impossible to uncheck, but 2 and 5 is possible to uncheck.
<ul>
<li><input type="checkbox" value="1">One</input></li>
<li><input type="checkbox" value="2">Two</input></li>
<li><input type="checkbox" value="3">Three</input></li>
<li><input type="checkbox" value="4">Four</input></li>
<li><input type="checkbox" value="5">Five</input></li>
<li><input type="checkbox" value="6">Six</input></li>
<li><input type="checkbox" value="7">Seven</input></li>
</ul>
// JavaScript
var el = document.getElementsByTagName("input");
var lastChecked = null;
// Iterate through every 'input' element and add an event listener = click
for(var i = 0; i < el.length; i++){
el[i].addEventListener("click", myFunction);
}
function myFunction() {
// In this statement we check, which input is checked..✓
if (!lastChecked) {
lastChecked = this;
return;
}
// Declaring 'from' and 'to' and getting index number of an array-like inputs
var from = [].indexOf.call(el, this);
var to = [].indexOf.call(el, lastChecked);
/* Here we will know which 'check' will be the min and which will be the max with the
help of Math metods */
var start = Math.min(from, to);
var end = Math.max(from, to) + 1;
// Here we create an array from NodeList
var arr = Array.prototype.slice.call(el);
// Here we get a new array, where we declare the start and the end
// Start is the min, end is the max
var slicedArr = arr.slice(start, end);
// Now we iterate through every sliced input, and set its attribute to checked
for(var j = 0; j < slicedArr.length; j++){
slicedArr[j].checked = lastChecked.checked;
}
lastChecked = this;
}
Thank you for any help guys. It is my first post on stackoverflow by the way, so I'm verry sorry if I didn't post it correctly. Thank you.
It's impossible to make checkboxes uncheckable.
Sure, you can use
document.getElementById("elemnt-id").disabled = true;
or via
disabled attribute in html,
but there's always a way to uncheck them manually via Developer tools. So you should have some validation on server too.
Get the element via attribute selector
for (let i=start; i<=end; i++){
document.querySelector(`[value="${i}"]`).disabled = true;
}
Here it is building the string in the selector with template literals
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
And just setting the disabled attribute in the checkboxes via Javascript
document.querySelector('[value="7"]').disabled = true;
it will get an HTML like
<input type="checkbox" value="7" disabled>
https://www.w3schools.com/jsref/prop_checkbox_disabled.asp
I am trying to make "toggle checkboxes" function, as below:
HTML Code:
<!-- "Check all" box -->
<input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox( this.getAttribute( 'id' ));" />
<!-- the other ones -->
<input type="checkbox" name="check" id="cbx_00_01" />
<input type="checkbox" name="check" id="cbx_00_02" />
<input type="checkbox" name="check" id="cbx_00_03" />
JavaScript:
function selectbox( eID ) {
// instead of writing the element id in the html code,
// i want to use "this.getAttribute( 'id' )"
var c = document.getElementById( eID );
// now when we've got the id of the element,
// let's get the required attribute.
var box = c.getAttribute( 'name' );
// set var i value to 0, in order to run "for i" loop
var i = 0;
for(i; i < box.length; i++) {
// now lets find if the main box (as box[0]) checked.
// if returns true (it has been checked), then check all - else -
// do not check 'em all.
if(box[0].checked == true) {
box[i].checked = true;
}
else {
box[i].checked = false;
}
}
}
I don't want any jQuery solution (even if it can be easier than pure js), so please avoid suggesting it. All I want to know is - If I'm wrong - what do you think I should do to solve this?
Thank you very much. every suggestion/tip is appreciated.
Your problem mainly seems to be that you are iterating over the checkbox name, not the checkboxes with that name.
var box = c.getAttribute( 'name' );
Now, box is equal to "check", so box[0] is "c", box[1] is "h" etc.
You need to add this:
var boxes = document.getElementsByName(box);
And then iterate over boxes.
Of course, at that point, you may want to rename your variables too.
Given the name in the variable box, you can check all boxes with the same name like this:
Array.prototype.forEach.call(document.getElementsByName(box), function(el) {
el.checked = true;
});
(Array.prototype.forEach.call is used to loop over the "fake-array" returned by getElementsByName because the NodeList class doesn't have forEach.)
I think you can further simply your code by not passing the element's ID to your function, but directly the name (selectbox(this.name)). Also note that you can access ID and name using .id and .name instead of using getAttribute.
You can make it simple.
HTML Code:
input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox(this.getAttribute('name'));" />
<input type="checkbox" name="check" id="cbx_00_01" />
<input type="checkbox" name="check" id="cbx_00_02" />
<input type="checkbox" name="check" id="cbx_00_03" />
Javascript:
function selectbox(eID) {
var checkBoxes = document.getElementsByName(eID);
for (var i = 0; i < checkBoxes .length; i++) {
if (checkBoxes[0].checked) {
checkBoxes[i].checked = true;
}
else {
checkBoxes[i].checked = false;
}
}
}
I have a poll with a couple a questions. Here is html code
<form id="pool">
<div class="questions>
<input type="radio" name="sex">Male
<input type="radio" name="sex">Female
</div>
<div class="questions>
<input type="radio" name="hair">Brown
<input type="radio" name="hair">Blonde
</div>
.... a lot of qestions div's
</form>
What to do so after the form is submitted to be sure that there is a checked radio button in all div`s ?
If you know how many groups you have you can just do:
if($('#pool input:radio:checked').length < numGroups){
// At least one group isn't checked
}
Otherwise you need to count the number of groups first. I can't think of any way to do this better then:
var rgroups = [];
$('#pool input:radio').each(function(index, el){
var i;
for(i = 0; i < rgroups.length; i++)
if(rgroups[i] == $(el).attr('name'))
return true;
rgroups.push($(el).attr('name'));
}
);
rgroups = rgroups.length;
if($('#pool input:radio:checked').length < rgroups)
alert('You must fill in all the fields.');
else
alert('Thanks!');
set default values or create handler for submit button and check if some values was checked. If no radio button is checked, show error message and do not submit form ( return false)
Untested code, but this is the idea:
if($('#pool').children().length == $('pool
div').find('#pool input:radio:selected').length) {
//do stuff
}
You can use the jquery validate plugin
from my experience this plugin is very efficient
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
I have two forms, one with a radio button that users must select to edit.
[form name="A"]
<li>[input type="radio" name="BookItem" value="1" /]</li>
<li>[input type="radio" name="BookItem" value="2" /]</li>
<li>[input type="radio" name="BookItem" value="3" /]</li>
[form]<p>
After "BookItem" is selected from form (A) I call the $("#EditFormWrapper").load("callEditData.cfm? ID="+ID); function to load the second form (B)
<div id="EditFormWrapper"><div></p>
<!---// begin dynamic form generated by external file callEditData.cfm //--->
[form id="editForm" name="B"]
<ul class="hourswrapper">
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="AM2Hrs1" /> 2 Hours AM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="PM2Hrs1" /> 2 Hours PM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="AM2Hrs2" /> 2 Hours AM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="PM2Hrs2" /> 2 Hours PM</li>
</ul>
[input type="image" src="images/submit-btn.gif" id="addBTN" name="addBTN" class="buttons" alt="SubmitRrequest" /]
[input type="image" src="images/cancel-btn.gif" id="editBTNcancel" name="editBTNcancel" class="buttons" alt="Cancel Request" /]
[/form]
<!---// end dynamic form from external file //--->
I want to uncheck the radio button on form (A) when user click on cancel button (editBTNcancel) in form(B).
Here's my script:
$("#editBTNcancel").live("click", function(event){
event.preventDefault();
$("#EditFormWrapper").slideUp("fast").empty();
//$('.TOR2Hours').removeAttr('checked');
$('.TOR2Hours').attr('checked', false);
});
I hope I clearly state my problem, any suggestion would be greatly appreciated!
you can access form like so ...
var exampleForm = document.forms['form_name'];
then loop through the form
for( var i=0; i<exampleForm.length; i++ ){
alert( exampleForm[i].type );
}
you can test for checked like so ...
if( exampleForm[i].checked )
to deselect the checked radio button try ...
exampleForm[i].checked=false;
the final code would look like this ...
var exampleForm = document.forms['form_name'];
for( var i=0; i<exampleForm.length; i++ ){
if( exampleForm[i].type ) == 'radio' && exampleForm[i].checked == true ){
exampleForm[i].checked = false;
}
}
I'm not sure exactly what you want but you might try using a reset input.
<input type='reset' />
Seeing as this is pretty much the easiest DOM task there is and works in every scriptable browser, I suggest not using the jQuery methods for it:
$(".TOR2Hours")[0].checked = false;
The other thing that ocurs to me is whether your selector is correct. Did you mean to select a set of elements by class or should it be an ID selector?
Your selector is simply wrong.
If you want to uncheck the radio button from first form you should use $('input[name="BookItem"]') and not $('.TOR2Hours') :
$("#editBTNcancel").on("click", function(event){
$("#EditFormWrapper").slideUp("fast").empty();
$('input[name="BookItem"]').attr('checked', false);
});
As far as which method to use to uncheck radio buttons, The following 3 methods should all work:
$('input[name="BookItem"]').attr('checked', false);
$('input[name="BookItem"]').removeAttr('checked');
$('input[name="BookItem"]').prop('checked', false);
However, check out jQuery's docs on jQuery prop() for the difference between attr() and prop().
I just discovered a great solution to this problem.
Assuming you have two radios that need to be able to be checked/unchecked, implement this code and change what's necessary:
var gift_click = 0;
function HandleGiftClick() {
if (document.getElementById('LeftPanelContent_giftDeed2').checked == true) {
gift_click++;
memorial_click = 0;
}
if (gift_click % 2 == 0) {document.getElementById('LeftPanelContent_giftDeed2').checked = false; }
}
var memorial_click = 0;
function HandleMemorialClick() {
if (document.getElementById('LeftPanelContent_memorialDeed2').checked == true) {
memorial_click++;
gift_click = 0;
}
if (memorial_click % 2 == 0) { document.getElementById('LeftPanelContent_memorialDeed2').checked = false; }
}
:) your welcome
I use this way to solve your problem in ASP.net, check this..
radioButton.InputAttributes["show"] = "false";
string clickJs = " if(this.show =='true'){this.show ='false'; this.checked = false;}else{this.show='true'; this.checked = true;};";
radioButton.Attributes["onClick"] = clickJs;
In asp.net, you can use this way to add an attribute. And you can also to add an attribute manually to the radioButton, and do the function(clickJs) to change the ckecked attributes!!!