Jquery array validation + php - php

I have a checkbox group in my html form.The check box group contains array.
My question is how validate the checkbox array using jquery and get the array value in php
The code given below
<input type="checkbox" name="go[]" value="1" /><label>Married</label><br>
<input type="checkbox" name="go[]" value="2" /><label>Widowed</label><br>
<input type="checkbox" name="go[]" value="3" /><label>Single</label><br>
<input type="checkbox" name="go[]" value="4"/><label>Minor</label>
Thanks in advance.

I think you're trying to use the jQuery Validation plugin to make sure that at least one checkbox from your group is checked.
The Validation plugin doesn't like input names with brackets in them. Try this in your form's validate method:
rules: {
'go[]': { //since it has brackets, the name must be in quotes to work
required: true,
minlength: 1
}

If you mean how to validate check boxes because they contain [], here is one solution using ids instead:
<script type="text/javascript">
function validate()
{
var proceed = true;
for(var i = 1; i <= 4; i++)
{
if (!$("#" + i).is(':checked'))
{
proceed = false;
break;
}
}
if (proceed == true)
{
return true;
}
else
{
alert('All Fields Are Required !!');
return false;
}
}
</script>
And the html form might look like this:
<form action="frm" method="post" onsubmit="return validate();">
<input type="checkbox" id="1" name="go[]" value="1" /><label>Married</label><br>
<input type="checkbox" id="2" name="go[]" value="2" /><label>Widowed</label><br>
<input type="checkbox" id="3" name="go[]" value="3" /><label>Single</label><br>
<input type="checkbox" id="4" name="go[]" value="4"/><label>Minor</label>
<br />
<input type="submit">
</form>
For PHP:
// get checkboxes array
$chk_array = $_POST['go'];
Now you can manipulate $chk_array array in any way you want:
Note:
$chk_array[0] // contains your 1st checkbox value
$chk_array[1] // contains your 2nd checkbox value
$chk_array[2] // contains your 3rd checkbox value
$chk_array[3] // contains your 4th checkbox value
In php, arrays start from 0 index.
Thanks

Related

Make checkbox return false when unchecked

I have a form looking like:
<form>
<input type"checkbox" name="checked[(unique_id)]">
<input type"checkbox" name="checked[(unique_id)]">
<input type"checkbox" name="checked[(unique_id)]">
<input type"checkbox" name="checked[(unique_id)]">
</form>
The number of checkboxes will variate from time to time so when processing this data with PHP I have to loop the _POST['checked'] array.
My problem is that I want to take actions both when a checkbox is checked and when it's not. But only the the checked checkboxes will be added to the _POST['checked'] array.
<form>
<input type="checkbox" key="1"/>
<input type="hidden" name="checked[1]" value="false">
<input type="checkbox" key="2"/>
<input type="hidden" name="checked[2]" value="false">
<input type="checkbox" key="3"/>
<input type="hidden" name="checked[3]" value="false">
<input type="checkbox" key="4"/>
<input type="hidden" name="checked[4]" value="false">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('[key]').change(function () {
var key = $(this).attr('key');
$($('[name="checked[' + key + ']"]')).val($(this).is(':checked') ? 'true' : 'false');
});
});
</script>
here is what i'm doing
i'm using two inputs one is checkbox without name so it won't be sent to php
, the other is hidden won't be shown to the user but it is what will be sent to php
then with jquery when the user check the box jquery change the value of the hidden input to true and when uncheck it change the value to false
so the value will always be send to the php with value true or false as string
you can change the value you want to send to php by changing this
.is(':checked')?'true':'false')
to something like that .is(':checked')?1:0) to send 1 and 0 instead of true and false
another solution is rybo111 solution
<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">
it will send the two options but if the checkbox is checked it will override the first option
but it is not reliable 100% and it will send more data to the server
read more about that in POSTing Form Fields with same Name Attribute
so if you want to use simple solution without js use the "html only"
if you want 100% reliable solution use the "js"
Here's a technique I've seen before:
<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">
The reason this works is because when values with the same name are sent more than once, only the last value is accepted.
In my opinion, a better way is to simply use isset($_POST['...']) or in_array($_POST['...']).
Add value="true" to each checkbox input element.
And change your PHP code to :
$checked_arr = [];
foreach($_POST["checked"] as $checked){
if($checked == "true"){
// do what you want to do
}
}
Another Solution is server-side solution that I think is too fast and easy.
client side:
Just use fresh HTML :
<input type="checkbox" name="checked1" value="value_checked" ... />
server side:
make global function like this:
function getVal(&$var, $default = '') {
if (!isset($var) || empty($var) || is_null($var))
$var = $default;
return $var;
}
then use where you want to read some value that you don't know is set or not.
like this:
$checked_value = getVal($_POST["checked1"],false);
or
$checked_value = getVal($_POST["checked1"],"value_not_checked");
I hope useful to another one.
This is best approach according to my experience
<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">

How to check Checkbox not checked in foreach

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.

Validating dynamic radio button group

I am trying to validate the values of a radio button group in php.
The radio buttons are dynamically created in the form.
I can validate the radio button if it is only one radio group, for example.
<form>
<input type="radio" name="radio1">
<input type="radio" name="radio1">
</form>
this is for passing values of radio button
if(isset($_POST['radio1']))
{
*some codes
}
Since the radio buttons in my form are dynamically created, the names of the radio groups increment like radio1, radio2, radio3 so on.
How can I make validation for this dynamic radio button group?
Better create radio button with name as array. Like
<form method="post">
<input type="radio" name="radio[1]">
<input type="radio" name="radio[2]">
</form>
and server side you can check with a foreach
foreach($_POST['radio'] as $key=>$radio){
if($radio == "on"){
echo "$key is checked";
}
}
Try this
<form>
<input type="radio" class="rdo" name="radio[]">
<input type="radio" class="rdo" name="radio[]">
.....
<input type="radio" class="rdo" name="radio[]">//n value
</form>
var arr = new Array();
$('.rdo:checked').each(function() {
arr.push($(this).val());
});
In server side
$i=0;
if(count($_POST['radio'])==0){
return false;
}
foreach($_POST['radio'] AS $rs){
if($rs!=''){
//Some code
}
else{
$i++;
}
}
if($i==count($_POST['radio'])){
return false;
}else{
//some code
}
You can try using radio elements as array like below:
<form method="post">
<input type="radio" name="radio[0]" value="0.1">
<input type="radio" name="radio[0]" value="0.2">
<input type="radio" name="radio[1]" value="1.1">
<input type="radio" name="radio[1]" value="1.2">
<input type="submit" name="s" value="Submit" />
</form>
and from server try
if(isset($_POST['radio'])){
echo "<pr>";
print_r($_POST);
}

Multiple Checkboxes array with checked and unchecked values

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>

Count checked checkboxes

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 &nbsp
<input type="checkbox" name="Personality_1.2" value="D" />Adventurous &nbsp
<input type="checkbox" name="Personality_1.3" value="C" />Analytical &nbsp
<input type="checkbox" name="Personality_1.4" value="S" />Adaptable<br /><br />
2.<input type="checkbox" name="Personality_2.1" value="I"/>Playful &nbsp
<input type="checkbox" name="Personality_2.2" value="D" />Persuasive &nbsp
<input type="checkbox" name="Personality_2.3" value="C" />Persistent &nbsp
<input type="checkbox" name="Personality_2.4" value="S" />Peaceful<br /><br />
3.<input type="checkbox" name="Personality_3.1" value="I"/>Sociable &nbsp
<input type="checkbox" name="Personality_3.2" value="D" />Strong Willed &nbsp
<input type="checkbox" name="Personality_3.3" value="C" />Self-sacraficing &nbsp
<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";
}
?>

Categories