I have 6 checkboxes, one for each business day and one that says 'all'.
What i want to be able to do is uncheck all the other boxes if someone clicks the 'all' checkbox if that makes sense.
For example, if someone has clicked monday and wednesday ... then they come in and click the 'all' checkbox, then the monday and wednesday checkbox should uncheck.
Cheers,
This is not you want, but seems to be more sensible.
HTML
<input type="checkbox" id="chkAll" />
<br />
<input type="checkbox" id="chkMonday" class="child" />
<input type="checkbox" id="chkTuesday" class="child" />
<input type="checkbox" id="chkWednesday" class="child" />
<input type="checkbox" id="chkThursday" class="child" />
<input type="checkbox" id="chkFriday" class="child" />
<input type="checkbox" id="chkSaturday" class="child" />
<input type="checkbox" id="chkSunday" class="child" />
jQUery
$(function(){
$("#chkAll").change(function(){
if (this.checked) {
$("input:checkbox.child").attr("checked", "checked");
}
else {
$("input:checkbox.child").removeAttr("checked");
}
});
});
See a working demo
See an updated version which handles change in the child checkboxes also.
jquery and some code like this should do it.
$('#all-id').change(function(){
if($('#all-id').is(':checked')){
if($('#monday-id').is(':checked')){
$('#monday-id').attr('checked', false);
} else {
$('#monday-id').attr('checked', true);
}
// etc
}
});
After you might want to put all the ids in an array and setup a loop or play with the structure of your document to be able to easily loop on all of those checkboxes
Related
I have html checkbox like this:
<form action="" method="post">
<input type="checkbox" name="language[]" value="php" />PHP<br />
<input type="checkbox" name="language[]" value="html" />HTML<br />
<input type="checkbox" name="language[]" value="java" />Java<br />
<input type="checkbox" name="language[]" value="c++" />C++<br />
<input type="submit" value="send" />
</form>
Now I want to detect the checkbox is not checked using this PHP
if($_POST)
{
if(empty($_POST['language']))
{
echo "bla";
}
else
{
foreach($_POST['language'] as $value)
{
echo 'Checked: '.$value.'
';
}
}
}
The output is always show the checbox checked.
My question is, how can I detect the checkbox is not checked?
Example I do not check PHP and Java.
You don't need to validate checkbox by checkbox in order to determine if they are checked or not, you won't get the unchecked checkboxes values at the time you send the form, so, sending the form like this:
<form action="" method="post">
<input type="checkbox" name="language[]" value="php" />PHP<br /> <!-- checked -->
<input type="checkbox" name="language[]" value="html" />HTML<br /><!-- checked -->
<input type="checkbox" name="language[]" value="java" />Java<br /><!-- unchecked -->
<input type="checkbox" name="language[]" value="c++" />C++<br /><!-- unchecked -->
<input type="submit" value="send" />
</form>
In your PHP, you will get an array as follows:
$_POST['languages'] = array("php", "html");
Now, lets say you have an array of all the values in order to check which ones you need to delete, and which ones you need to add, a rough code example would be as follows:
$allValues = array('php', 'html', 'java', 'c++');
$valuesForAdd = $_POST['language'];
$valuesForDeletion = array_diff($allValues, $valuesForAdd);
First you need the selectable items array in the backend:
$items = array('php','html','java','c++');
You have the posted (selected) languages array here:
$_POST['language']
Not selected languages array:
$not_selected_languages = array_diff($items,$_POST['language']);
I hope it helps.
Only 'checked' checkboxes get sent as parameters in a POST request.
If you want to know which aren't checked, you could have the value list stored on PHP side; then once you receive POST data - compare the array on PHP side with POST array.
$all_vals = array('php', 'c++', 'html', 'java');
$post_vals = $_POST['languages'];
foreach ($post_vals as $post_val)
if in_array($post_val, $all_vals)
$checkbox checked
else
$checkbox not checked
I assume this gives you enough liberty to do what you need.
I have a form that did submit 1 out of 8 radio buttons to a php $_POST super global array. Therefore, I needed some validation. I was kindly helped by being provided this code which works great:
$("#form").submit(function (event) {
if(!$(":radio:checked").length) {
alert("You must select at least one emotional state!");
event.preventDefault();
}
});
However, I have now been asked to have 2 sets of 8 radio buttons in which the user selects 2 answers instead of the initial 1 answer. I need the code to be able to determine that at least one radio button from each set of 8 buttons has been selected before the form is submitted. At the moment the code checks to see if any radio buttons have been selected, then as soon as just 1 buttons is selected, the function is satisfied and transitions to the next page, which is not what I want.
EDIT
Buttons code:
<p><input type="radio" value="happy" name="perceived_emotion">Happy
<input type="radio" value="excited" name="perceived_emotion">Excited
<input type="radio" value="angry" name="perceived_emotion">Angry
<input type="radio" value="frustrated" name="perceived_emotion">Frustrated
<input type="radio" value="miserable" name="perceived_emotion">Miserable
<input type="radio" value="sad" name="perceived_emotion">Sad
<input type="radio" value="tired" name="perceived_emotion">Tired
<input type="radio" value="relaxed" name="perceived_emotion">Relaxed</p>
<p><input type="radio" value="happy" name="induced_emotion">Happy
<input type="radio" value="excited" name="induced_emotion">Excited
<input type="radio" value="angry" name="induced_emotion">Angry
<input type="radio" value="frustrated" name="induced_emotion">Frustrated
<input type="radio" value="miserable" name="induced_emotion">Miserable
<input type="radio" value="sad" name="induced_emotion">Sad
<input type="radio" value="tired" name="induced_emotion">Tired
<input type="radio" value="relaxed" name="induced_emotion">Relaxed</p>
Here is the form code:
<form id="form" action="audio_handler.php?id=1" method="POST">
<div id="perceived_emotions">
<?php include("includes/induced_emotion_buttons.php"); ?>
</div>
<br />
<div id="induced_emotions">
<?php include("includes/perceived_emotion_buttons.php"); ?>
</div>
<p class="right"><input type="submit" name="submit" value="Submit"></p>
</form>
What you want to do is use the [name="value"] selector in JQuery in conjunction with the :checked selector. So your new code would be:
if(!$('input[name="perceived_emotion"]:checked').length) {
alert("You must select at least one perceived emotional state!");
event.preventDefault();
return false;
}
if(!$('input[name="induced_emotion"]:checked').length) {
alert("You must select at least one induced emotional state!");
event.preventDefault();
return false;
}
All of that wrapped into the form event.
EDIT: Since you only want to display one dialog at once, just add return false; in each if statement.
So i have this line of code that will repeat different times in a form.
<input type="checkbox" name="checkbox[]" /> !checked
<input type="checkbox" name="checkbox[]" /> !unchecked
<input type="checkbox" name="checkbox[]" /> !checked
<input type="checkbox" name="checkbox[]" /> !unchecked
The !checked show that the checkbox was checked and the !unchecked shows that the checkbox was not checked.
How can i create a php array to get values of checked and unchecked checkboxes in order like this :
array( 0 => checked, 1 => unchecked, 2 => checked, 3 => unchecked );
Momentarily i can get just the checked value with $_POST["checkbox"] but i cannot get the unchecked value.
First of all you need to put a value to your checkboxes:
<input type="checkbox" name="checkbox[]" value="checkboxNchecked" /> !checked
You can't really distinguish your checkboxes otherwise.
Then: Your checkboxes will either return a value if they are checked or will be ignored when they are unchecked. You will not get a NULL, FALSE or other value. It will simply not be transfered via POST/GET to your php script as if it wasn't in yout HTML code. This covers the topic: Does <input type="checkbox" /> only post data if it's checked?
If you know how many checkboxes are around and what they are called - no problemo señor - but if you don't, you'll need to find a way around. If you tell us what the nature of your checkboxes are, we can help you find a tailored solution.
you can use jquery and ajax. In your submit event get all values from the form and submit it by ajax. you can get unchecked value in jquery like this:
$("input:checkbox:not(:checked)")
or
if ($('#idOfYourCheckBox:checked').length > 0) {
//its checked
}
else {
//not checked
}
This will print only checked fields, because unchecked ones are not sent to server.
You will have to do some javascript and hidden field tricks.
Take a look here
Post the checkboxes that are unchecked
<input type="checkbox" name="checkbox[n1]" /> !checked
<input type="checkbox" name="checkbox[n2]" /> !unchecked
<input type="checkbox" name="checkbox[n3]" /> !checked
<input type="checkbox" name="checkbox[n4]" /> !sdsk
foreach($_POST['checkbox'] as $key => $value){
$checkbox[$key] = 'checked';
}
print_r($checkbox); // your new array
Solved:
Declaration of form...
<form id="form1" name="form1" method="post" action="xx.php" onSubmit="set_hidden_value()">
<input name="arrayofchecks" type="hidden" value="toset" />
...
OnSubmit:
function set_hidden_value()
{
var checkstring = "";
for (var i=0; i < $('#checkbox').length; i++)
{
if ($('#checkbox')[i].checked)
{
checkstring = checkstring + "1";
}
else
{
checkstring = checkstring + "0";
}
}
$('#arrayofchecks').val(checkstring);
And the result is a string with values checked and unchecked (1 and 0)...
In my case, i use ajax for intercept submit and do set_hidden_value here...
If you are using a server side language like PHP, there is an easier method than using hidden fields to supply default or writing javascript (both may fail if the user's device/browser doesn't support that method).
<input type="checkbox" value="choice1" name="checkbox[]" />
<input type="checkbox" value="choice2" name="checkbox[]" />
<input type="checkbox" value="choice3" name="checkbox[]" />
This method doesn't return unchecked items, but it specifically identifies which items were checked. Otherwise, if the checkboxes all have the same value, all you get is one, two or 3 values repeated with no idea which item was checked. However, assuming choice2 was checked with the above method, it's pretty easy then to figure out that item 1 and 3 therefore were not checked.
Please check below code.
$("button").click(function () {
var i=0;
var cbox=[];
$("input[name='cbox']").each(function () {
if($(this).is(':checked')) {
cbox[i++] = $(this).val();
}else{
cbox[i++] = "unchecked";
}
});
console.log(cbox);
i = 0;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<button>Click</button>
I am new to HTML, I have a list of checkboxes on a form in an HTML page.
Each checkbox on each line represents a different category "I" "D" "C" and "S".
Part of my code is as follows:
<form>
1.<input type="checkbox" name="Personality_1.1" value="I"/>Animated  
<input type="checkbox" name="Personality_1.2" value="D" />Adventurous  
<input type="checkbox" name="Personality_1.3" value="C" />Analytical  
<input type="checkbox" name="Personality_1.4" value="S" />Adaptable<br /><br />
2.<input type="checkbox" name="Personality_2.1" value="I"/>Playful  
<input type="checkbox" name="Personality_2.2" value="D" />Persuasive  
<input type="checkbox" name="Personality_2.3" value="C" />Persistent  
<input type="checkbox" name="Personality_2.4" value="S" />Peaceful<br /><br />
3.<input type="checkbox" name="Personality_3.1" value="I"/>Sociable  
<input type="checkbox" name="Personality_3.2" value="D" />Strong Willed  
<input type="checkbox" name="Personality_3.3" value="C" />Self-sacraficing  
<input type="checkbox" name="Personality_3.4" value="S" />Submissive<br /><br />
I need to find out how many value "I" checkboxes have been checked, how many value "D" checkboxes have been checked, and so on, and then display the total of each category when the form is submitted.
Such a: "Five D's have been checked" "Three C's have been checked"
Is there a way I can do this with Javascript or PHP? If so can anyone help direct me to figure out how to do so?
Well, with PHP, assuming your submitting the form with POST:
$counts = array_count_values($_POST);
And you'll get an associative array with the values as keys and counts as values. So if for example 3 D's have been checked, $counts['D'] will hold "3".
As an example, you can use something like this:
window.onload = function () {
document.getElementById("btn1").onclick = function () {
var allChk = document.getElementsByTagName("input"),
counts = {},
i, j, cur, val;
for (i = 0, j = allChk.length; i < j; i++) {
cur = allChk[i];
if (cur.type === "checkbox") {
if (!(cur.value in counts)) {
counts[cur.value] = 0;
}
if (cur.checked) {
counts[cur.value]++;
}
}
}
for (val in counts) {
console.log("There are " + counts[val] + " " + val + "'s checked");
}
};
};
DEMO: http://jsfiddle.net/Dwjez/1/
Click the button, after checking some checkboxes, and look at your console to see the results. It just finds all checkboxes, and stores the number of checked ones, per value, in an object literal...then the final loop is there just to print the results in the console.
This was just a simple example with event handling, but I'd suggest looking at addEventListener vs onclick to see another way to handle events (with addEventListener).
jquery-:
var numberOfCheckboxesSelected = $('input[type=checkbox]:checked').length;
javascript--:
var checkboxLength = document.forms["formName"].elements["checkbox[]"].length;
var checkboxes = document.forms["formName"].elements["checkbox[]"];
for(var i = 0; i < checkboxLength; ++i) {
if(checkboxes[i].checked) {
// do stuff
}
}
how about...
var getCount = function(type) {
return document.querySelectorAll('input[value='+type+']:checked').length;
}
alert(getCount('A') + "As have been selected");
and it looks like you would be better off using a radio group instead of checkboxes. From looking at your html, do you want the user to be able to select more than one item in each section?
Here is the code you want. Try it and let me know.
<HTML>
<HEAD>
<TITLE>Document Title</TITLE>
</HEAD>
<BODY>
<FORM NAME="f1" action="next_page.php" method="post">
<input type="checkbox" name="chkGuar[]" value="mike"> Mike<br />
<input type="checkbox" name="chkGuar[]" value="joy"> Joy<br />
<input type="checkbox" name="chkGuar[]" value="harry"> harry<br />
<input type="checkbox" name="chkGuar[]" value="watson"> watson<br />
<input type="checkbox" name="chkGuar[]" value="george"> george<br />
<input type="checkbox" name="chkGuar[]" value="peter"> Peter<br />
<input type="submit" name="chksbmt" value="Send" />
<!-- <div id="myrow" style="visibility:hidden">
<input type = text name ='txtGRTNo' tabindex = 19 size="20">
</div>
<div width="338" align="left" colspan="3" height="12"></div> !-->
</FORM>
</BODY>
</HTML>
next_page.php
<?php
if(isset($_POST['chksbmt'])){
$counts = count($_POST['chkGuar']);
echo "this is the next page. you checked $counts checkbox <br /><br />";
for($i=1;$i<=$counts;$i++){
echo "<input type='text' style='border:1px solid #000;' value='your text box here' /><br/><br/>";
}
}
You should write your form code like this:
<form>
1.<input type="checkbox" name="chkI[]" value="I1"/>Animated
<input type="checkbox" name="chkD[]" value="D1" />Adventurous
<input type="checkbox" name="chkC[]" value="C1" />Analytical
<input type="checkbox" name="chkS[]" value="S1" />Adaptable
2.<input type="checkbox" name="chkI[]" value="I2"/>Playful
<input type="checkbox" name="chkD[]" value="D2" />Persuasive
<input type="checkbox" name="chkC[]" value="C2" />Persistent
<input type="checkbox" name="chkS[]" value="S2" />Peaceful
3.<input type="checkbox" name="chkI[]" value="I3"/>Sociable
<input type="checkbox" name="chkD[]" value="D3" />Strong Willed
<input type="checkbox" name="chkC[]" value="C3" />Self-sacraficing
<input type="checkbox" name="chkS[]" value="S3" />Submissive
</form>
Look at the "name" and "value" attributes. I made I change to the values of them.
You say:
I need to find out how many value "I" checkboxes have been checked, how many value "D" checkboxes have been checked, and so on, and then
display the total of each category when the form is submitted.
If you make a submit...
<?php
if(!empty($_GET['chkD'])) {
$counterChkD = 0;
foreach ($_GET['chkD'] as $chkD){
echo $chkD."\n";
//echoes the value set in the HTML form for each checked checkbox associated with the "D" value
//so, if I were to check "Adventurous", "Persuasive", and "Strong Willed" it would echo value D1, value D2, value D3.
$counterChkD++;
}
echo "# of 'D-CheckBoxes' checked: ".$counterChkD."\n";
}
?>
I have a web app (PHP) and I have to make this change. I am more of a database, scripting guy, please bear with me on this one!
I have 8 check boxes (think numbered 1~8) in a form. I have to implement a condition where in :
If one of the first 4 checkboxes are checked (only one checkbox can be checked in the first 4),
Then the next 4 checkboxes should be disabled
Else the next 4 checkboxes should be enabled.
My solution :
Make the first 4 checkboxes radiobuttons to confirm to the only one
checkbox can be selected condition.
Disable/Enable the next 4 checkboxes based on the above action. So,
if the radiobutton is not selected, then the next 4 checkboxes should
be available for selection.
I have to actually disable the checkboxes rather than hide using jQuery, so the checkboxes should be solidgray (uncheckable) when disabled.
Sample code (stripped off some formatting mess for others looking for a similar solution) :
<div>
<input type="checkbox" name="check1" value="1" id="check1" <?php if (!empty($rows['check1'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check2" value="1" id="check2" <?php if (!empty($rows['check2'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check3" value="1" id="check3" <?php if (!empty($rows['check3'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check4" value="1" id="check4" <?php if (!empty($rows['check4'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check5" value="1" id="check5" <?php if (!empty($rows['check5'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check6" value="1" id="check6" <?php if (!empty($rows['check6'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check7" value="1" id="check7" <?php if (!empty($rows['check7'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check8" value="1" id="check8" <?php if (!empty($rows['check8'])) { echo 'checked="checked"'; } ?> />
</div>
My requests :
What is the most efficient way of doing this? (simple without complicating the problem)
Any sample code is greatly appreciated.
I think this is what you're looking for. You can achieve it using .index() to get current clicked checkbox. .slice() is used to get all elements at index 4 and after.
$('input[type=checkbox]').change(function(){
var $linputs = $('input[type=checkbox]').slice(4);
var $this = $(this);
$linputs.prop('disabled',($this.index() < 4 && this.checked));
if($this.index() < 4 && this.checked){
$linputs.prop('checked',false);
}
});
FIDDDLE
Or is it something like this that you want? Where only one of the first four checkboxes can be checked. If one is checked then all the others will be disabled.
$('input[type=checkbox]').change(function(){
var $this = $(this);
$(linputs).prop('disabled',($this.index() < 4 && this.checked));
if($this.index() < 4 && this.checked){
$(linputs).prop('checked',false);
}
});
http://jsfiddle.net/h5wDr/
EDIT:
if you have other checkboxes in the page and want to be able to separate them from this logic, you can add context in the selector so it keeps this code isolated to only those within this div like so
<div id='test'>
<input type="checkbox" name="check1" value="1" id="check1" >first
<input type="checkbox" name="check2" value="1" id="check2" >second
<input type="checkbox" name="check3" value="1" id="check3" >third
<input type="checkbox" name="check4" value="1" id="check4" >fourth
<input type="checkbox" name="check5" value="1" id="check5" >fifth
<input type="checkbox" name="check6" value="1" id="check6" >sixth
<input type="checkbox" name="check7" value="1" id="check7" >seventh
<input type="checkbox" name="check8" value="1" id="check8" >eight
</div>
Then just add the context
var $inputs = $('input[type=checkbox]', $('#test'));
// this will only select checkboxes within the element with id=test
http://jsfiddle.net/h5wDr/2/
<div>
<input type="checkbox" name="check1" value="1" id="check1" />
<input type="checkbox" name="check2" value="1" id="check2" />
<input type="checkbox" name="check3" value="1" id="check3" />
<input type="checkbox" name="check4" value="1" id="check4" />
<input type="checkbox" name="check5" value="1" id="check5" />
<input type="checkbox" name="check6" value="1" id="check6" />
<input type="checkbox" name="check7" value="1" id="check7" />
<input type="checkbox" name="check8" value="1" id="check8" />
</div>
<script>
$(document).ready(function () {
var $firstFourChecks = $("#check1,#check2,#check3,#check4");
var $lastFourChecks = $("#check5,#check6,#check7,#check8");
$firstFourChecks.on('click', function (e) {
var isCheck = $(this).is(':checked');
$firstFourChecks.not($(this)).prop('checked', false);
$(this).prop('checked', isCheck);
if (isCheck) {
$lastFourChecks.prop("disabled", true).prop('checked', false);
} else {
$lastFourChecks.prop("disabled", false);
}
});
});
</script>
This is entirely done in javascript, and is agnostic to the fact you are using php. Essentially, we make sure in the first four for you have not selected, they are set to false. Then we toggle the state of the one clicked.
If you clicked something on in your first four the last four are turned off and disabled, otherwise they are renabled. This matches the posted pseudocode.
You should be able to paste this directly in. The selectors are cached for speed reasons.
http://jsfiddle.net/L4qeN/ see it here.
Edit: wow looks like someone beat me to the punchline by only a few minutes. We did use very different methods; however.
You would have to try it yourself, but I would do something like (using javascript):
Add a class to every checkbox of the first group and another class to every checkbox of the second group;
Check for change events for the first class, turn off all of the first group but the clicked one;
Check if any of the first group is selected and activate / deactivate the second class group accordingly.
Give your first four checkboxes one class and then your second four a second class and then add onclick handlers to all the first checkboxes:
$('.firstfour_class').click(
if $('input:checkbox:checked.firstfour_class').length > 1){
//code to turn OFF the second four and make them unchecked
} else {
//code to turn ON the second four
}
})
Check out the jQuery :checked selector.