I have a form with multiple checkboxes. I want to allow the user to select at least 1 in each checkbox field, if the user does not check any of the options in the checkbox, a message will display "You have to select at least one." How do I do it? I have here some of my codes:
<div>
<div><span class="font-2">Categories:</span></div>
</div>
<div class = "addinfo">
<?php $categories = array('Breakfast', 'Lunch', 'Dinner', 'Snack', 'Grill', 'Buffet', 'Fast Food');
$values = explode(',' , $row['categories']);
?>
<?php foreach($categories as $category) {
$cat='';
foreach($values as $value){
if($value == $category){
$cat ="checked";
}
?>
<input <?php echo $cat ?> type="checkbox" name="category[]" value="<?php echo $category?>"><?php echo $category?><br>
<?php }
}?>
</div>
form
<form method = "POST" action = "<?php echo base_url().'/index.php/AdminController/operation'?>">
AdminController
public function addResto(){
$this->load->model('AdminModel');
$this->AdminModel->insert();
$this->getRestos();
}
public function operation(){
if(isset($_POST['btn'])){
if(empty($_POST['id'])){
$this->addResto();
}
else{
$this->updatingResto();
}
}
}
public function updateResto($id){
$this->load->model('AdminModel');
$restaurantinfo['restaurantinfo']=$this->AdminModel->getResto($id);
$this->load->view('admin/UpdateRestoPage',$restaurantinfo);
}
public function updatePage(){
$this->load->view('admin/UpdateRestoPage');
}
public function updatingResto(){
$id = $_POST['id'];
$this->load->model('AdminModel');
$this->AdminModel->update($id);
}
You should also check if there is a checkbox that is checked
public function operation(){
if(isset($_POST['btn'])){
if(empty($_POST['category'])){
$this->load->view('YOUR_VIEW_FILE',array('error'=>'category'));
}else if(empty($_POST['id'])){
$this->addResto();
}
else{
$this->updatingResto();
}
}
}
your view file add a condition
<?php
if(!empty($error) && $error=="category"){
?>
<script>alert("You have to select at least one.");</script>
<?php
}
?>
Add validation in your called php
<?php
$checked = false;
foreach($_POST["category"] as $key) {
if(!empty($key)) {
$checked = true;
}
}
if(!$checked) {
echo "<script>";
echo "alert('You have to select at least one.');";
echo "history.back();";
echo "</script>";
exit();
}
?>
in your controllers operation function use
if (isset($_POST['mycheckbox'])) {
echo "checked!";
} esle {
//send again with error message
}
Using this validation in javascript:
$("input:checkbox[name='a']:checked").length == 0
Example:
HTML code:
<from name='frm1' method='' action='POST'>
<label>Favorites:</label>
<span>sports</span><input type="checkbox" name="fav" value="1"/>
<span>music</span> <input type="checkbox" name="fav" value="2"/>
<span>reading</span> <input type="checkbox" name="fav" value="3"/>
<input type="button" value="validate">
</form>
Javascript code:
function validate() {
//replace with your own code here
if ($('input:checkbox[name="fav"]:checked').length == 0) {
alert("You have to select at least one.");
}
}
$("input[type='button']").click(validate)
It's just a simple example to demonstrate the use of :check selector(JQuery), you need to
change and embed it in your project!
try to add this in your html code:
<script type="text/javascript">
function check () {
var inputs = document.querySelectorAll("input[type='checkbox']");
for(var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
return true;
}
}
alert("You have to select at least one.");
return false;
}
</script>
This one will show the error before the page refreshes. And add something like this in your html :
<input type = "button" onclick = "check();">
UPDATE : try to replace your code with this.
<div>
<div><span class="font-2">Categories:</span></div>
</div>
<script type="text/javascript">
function check () {
var inputs = document.querySelectorAll("input[type='checkbox']");
for(var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
return true;
}
}
alert("You have to select at least one.");
return false;
}
</script>
<div class = "addinfo">
<?php $categories = array('Breakfast', 'Lunch', 'Dinner', 'Snack', 'Grill', 'Buffet', 'Fast Food');
$values = explode(',' , $row['categories']);
?>
<?php foreach($categories as $category) {
$cat='';
foreach($values as $value){
if($value == $category){
$cat ="checked";
}
?>
<input <?php echo $cat ?> type="checkbox" name="category[]" value="<?php echo $category?>"><?php echo $category?><br>
<?php }
}?>
<input type = "button" onclick = "check();">
</div>
Related
please click to view imagePHP CODE: this the code getting the value from database and use it to checked/unchecked checkbox.
<?php
$value = FALSE;
foreach ($LOCKPERIOD as $lp)
if ($lpg->pay_code == $lp->pay_code) {
if ($lp->generate_payslip == 1) {
$value = TRUE;
} else {
$value = FALSE;
}
}
?>
<input type="checkbox" id="checkbox" checked="<?php echo $value; ?>" >
Please follow following steps, i have edited your code.
<?php
$value = FALSE;
foreach ($LOCKPERIOD as $lp){
if ($lpg->pay_code == $lp->pay_code) {
if ($lp->generate_payslip == 1) {
$value = TRUE;
} else {
$value = FALSE;
}
}
<input type="checkbox" id="checkbox" <?php echo ($value==TRUE)? 'checked':'';?> >
}
?>
It will work. Kindly try it.
I am using checkboxes to query the database and I am struggling with this one, I am new to MySQL and PHP so sorry if this is simple!
Here is my code that I have...
<input type="checkbox" name="season2005" value="2005" <?php if(isset($_POST['season2005'])) echo "checked='checked'"; ?> > 2005-06
<input type="checkbox" name="season2006" value="2006" <?php if(isset($_POST['season2006'])) echo "checked='checked'"; ?> > 2006-07
<input type="checkbox" name="season2007" value="2007" <?php if(isset($_POST['season2007'])) echo "checked='checked'"; ?> > 2007-08
<input type="checkbox" name="season2008" value="2008" <?php if(isset($_POST['season2008'])) echo "checked='checked'"; ?> > 2008-09
<input type="checkbox" name="season2009" value="2009" <?php if(isset($_POST['season2009'])) echo "checked='checked'"; ?> > 2009-10
<input type="checkbox" name="season2010" value="2010" <?php if(isset($_POST['season2010'])) echo "checked='checked'"; ?> > 2010-11
<input type="checkbox" name="season2011" value="2011" <?php if(isset($_POST['season2011'])) echo "checked='checked'"; ?> > 2011-12
<input type="checkbox" name="season2012" value="2012" <?php if(isset($_POST['season2012'])) echo "checked='checked'"; ?> > 2012-13
<input type="checkbox" name="season2013" value="2013" <?php if(isset($_POST['season2013'])) echo "checked='checked'"; ?> > 2013-14
if (#$_POST['season2005'] == ""){ $season2005 = "0000"; } else { $season2005 = "2005"; }
if (#$_POST['season2006'] == ""){ $season2006 = "0000"; } else { $season2006 = "2006"; }
if (#$_POST['season2007'] == ""){ $season2007 = "0000"; } else { $season2007 = "2007"; }
if (#$_POST['season2008'] == ""){ $season2008 = "0000"; } else { $season2008 = "2008"; }
if (#$_POST['season2009'] == ""){ $season2009 = "0000"; } else { $season2009 = "2009"; }
if (#$_POST['season2010'] == ""){ $season2010 = "0000"; } else { $season2010 = "2010"; }
if (#$_POST['season2011'] == ""){ $season2011 = "0000"; } else { $season2011 = "2011"; }
if (#$_POST['season2012'] == ""){ $season2012 = "0000"; } else { $season2012 = "2012"; }
if (#$_POST['season2013'] == ""){ $season2013 = "0000"; } else { $season2013 = "2013"; }
$seasons = array($season2005,$season2006,$season2007,$season2008,$season2009,$season2010,$season2011,$season2012,$season2013);
$seasonpick = implode(",",$seasons);;
$matcharrays = array("AND season in ($seasonpick)");
At the moment all of the data is being queried to the database, so if nothing is selected them then part of query from this is "AND season in (0000,0000,0000,0000) etc
How would I go about only getting those selected into the array and if none are selected then the array would be blank.
Hope you understand what I mean!
Here is a working form with some checkboxes that will allow you to test and get the sql you intended.
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode(",", $dateArr);
$sql=".... and season in (".$dateSearch.")";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
echo "<input type=\"checkbox\" name=\"season[]\" value=\"".($i+2005)."\"> ".($i+2005);
}
?>
<input type="submit">
</form>
Output when 2009, 2010 and 2011 selected:
.... and season in (2009,2010,2011)
Okay, so how it works:
Checkboxes are best used when they all have the same name ending in a []. This makes it a nice array on it's own.
If post data is set, we then quickly throw an array unique over it (good habit for the most part in these types of queries) so that there are no duplicate values.
Then simply implode it into a string and pop it into the SQL query.
Edit: Added functionality to re-check checkboxes when submitted.
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode(",", $dateArr);
$sql=".... and season in (".$dateSearch.")";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
$chk="";
if(!empty($_POST['season']))
{
if(in_array($i+2005, $_POST['season']))
{
$chk=" checked=\"checked\" ";
}
}
echo "<input type=\"checkbox\" name=\"season[]\" ".$chk." value=\"".($i+2005)."\"> ".($i+2005);
}
?>
<input type="submit">
</form>
Edit 2: Just add quotes in the right places :)
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode("', '", $dateArr);
$sql=".... and season in ('".$dateSearch."')";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
$chk="";
if(!empty($_POST['season']))
{
if(in_array(($i+2005)."i", $_POST['season']))
{
$chk=" checked=\"checked\" ";
}
}
echo "<input type=\"checkbox\" name=\"season[]\" ".$chk." value=\"".(($i+2005)."i")."\"> ".($i+2005)."i";
}
?>
<input type="submit">
</form>
Edit 3: I feel like this is starting to really answer much more than one question :)
You can simply check the textbox to make sure it isn't empty and then append to a SQL string:
$sql="";
if(!empty($_POST['text1']))
{
$sql.=" and ftgf>= ".$_POST['text1']." ";
}
Having said that, I would strongly suggest that you NEVER allow the user to enter in parts of the actual SQL you will run - unless it is a closed/secure environment, which means NOT an ope website.
Insert the below code
$seasons = array($season2005,$season2006,$season2007,$season2008,$season2009,$season2010,$season2011,$season2012,$season2013);
//start
$seasons2 = array();
foreach ($seasons as $season)
{
if($season!=="0000")
{
array_push($seasons2,$season);
}
}
$seasonpick = implode(",",$seasons2);
//end
Working on a simple php code. When it press on only PH it show hello, and only on chlorine it show yello. When both is pressed it show sello.
<?php
if(isset($_POST['submit'])){
foreach($_POST['verdi'] as $animal){
if(isset($_POST['verdi[]==PH']))
{
echo "hello";
}
}
}
?>
<form name="input" action="" method="POST">
<input type="checkbox" name="verdi[]" value="PH">PH<br>
<input type="checkbox" name="verdi[]" value="Chlorine">Chlorine<br>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
You can do a simple check in PHP:
if( in_array("PH", $_POST["verdi"]) ){
echo "in array!";
}
if(isset($_POST['submit']) && is_array($_POST['verdi'])) {
$checked = array();
foreach($_POST['verdi'] as $animal) {
// you can do extra validation here.
$checked[] = $animal;
}
if(in_array("PH", $checked) && in_array("Chlorine", $checked)) {
echo "sello";
} else {
if(in_array("PH", $checked)) {
echo "hello";
} else if(in_array("Chlorine", $checked)) {
echo "yello";
}
}
}
Here is my PHP code:
<?php if (isset($mod['display']) && ($mod['display'] == "1")) { ?>
<input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" checked="checked" onclick="checkbox_click(this);" />
<?php } else { ?>
<input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" onclick="checkbox_click(this);" />
<?php } ?>
jQuery:
function checkbox_click(current) {
if($(current).is(':checked')) {
// do stuff....
} else {
// do stuff....
}
}
In the above code, when $mod['display'] is true, the checkbox is checked but it does not invoke checkbox_click() function. I tried onchange= instead of onclick= but it does not seem to have any effect. I need to keep the onclick or onchange in the field.
Try to use prop function for this,
Also you don't need to call function, you can create it by using jquery.on() function like,
$(function(){
$(document).on('click','.display_checkbox',function(){
if($(this).prop('checked')) {
// do stuff....
} else {
// do stuff....
}
});
});
And then remove onclick="checkbox_click(this);" from your html checkbox element
Updated
To initialize it on document ready
$(function(){
$('.display_checkbox').each(function(){
if($(this).prop('checked')) {
// do stuff....
} else {
// do stuff....
}
});
});
Read on() and prop()
Try this:
<?php if (isset($mod['display']) && ($mod['display'] == "1")) { ?>
<input class="display_checkbox selectedcheckbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" checked="checked" onclick="checkbox_click(this);" />
<?php } else { ?>
<input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" onclick="checkbox_click(this);" />
<?php } ?>
jQuery:
$(document).ready(function(){
var obj = $(".selectedcheckbox");
var found = obj.length;
if(found == 1)
{
checkbox_click(obj);
}
});
function checkbox_click(current) {
if($(current).is(':checked')) {
// do stuff....
} else {
// do stuff....
}
}
If you want function to be executed after page load, and also be axecuted every time checkbox state is changed you should do it this way:
<?php if (isset($mod['display']) && ($mod['display'] == "1")) { ?>
<input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" checked="checked" onclick="checkbox_click(this);" />
<?php } else { ?>
<input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" onclick="checkbox_click(this);" />
<?php } ?>
and in script:
function checkbox_click(current) {
if($(current).is(':checked')) {
// do stuff....
} else {
// do stuff....
}
}
$(function(){
$('.display_checkbox').each(function(){
checkbox_click($(this));
});
});
Also, I wouldn't do it that way. in this case, you should use onchange event binding.
Optimal solution i think would be:
<input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" <?php if (isset($mod['display']) && ($mod['display'] == "1")) { ?>checked="checked"<?php } ?> />
and javascript should look like this:
$(function(){
$('.display_checkbox').change(function(){
if($(this).is(':checked')) {
// do stuff....
} else {
// do stuff....
}
});
$('.display_checkbox').each(function(){
$(this).change();
});
});
I want to apply validation on multiple check boxes but question is how to do it?
<?php
mysql_connect("localhost","root","thisis");
mysql_select_db("my_database");
if(isset($_GET["q"]))
{
$my_q = $_GET['q'];
$q="select * from subjects where subj_code='$my_q'";
$rs=mysql_query($q);
for($i=0;$i<mysql_num_rows($rs);$i++)
{
$rd=mysql_fetch_object($rs);
?>
<input type="checkbox" name="subj[]" value="<?php echo $rd->subj_name; ?>" /><?php echo $rd->subj_name; ?>
<br />
<?php
}
}
?>
Try the below code.
obj = document.form1.elements("subj[]");
for (i = 0; i < obj.length; i++) {
if (obj[i].checked) {
alert("Your text");
return true;
}
}
Try This:
if($('input[name="sub[]"]:checked').length == 0) {
alert('No checkbox is checked');
return false;
}