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();
});
});
Related
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>
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";
}
}
}
My HTML+JS :
<head>
<script type="text/javascript">
function passList() {
var p=[];
$('input.first').each( function() {
if($(this).attr('checked')) {
p.push($(this).attr('rel'));
}
} );
$.ajax( {
url:'process.php',
type:'POST',
data: {list:p},
success: function(res) {
$("#result").html(res);
}
});
}
function passType() {
var q=[];
$('input.second').each( function() {
if($(this).attr('checked')) {
q.push($(this).attr('rel'));
}
} );
$.ajax( {
url:'process.php',
type:'POST',
data: {type:q},
success: function(res) {
$("#result").html(res);
}
});
}
</script>
</head>
<body>
<input type="checkbox" class="first" rel="list1" onclick="passList()">list1<br />
<input type="checkbox" class="first" rel="list2" onclick="passList()">list2<br />
<input type="checkbox" class="first" rel="list3" onclick="passList()">list3<br />
<input type="checkbox" class="first" rel="list4" onclick="passList()">list4<br />
<br><br><br>
<input type="checkbox" class="second" rel="type1" onclick="passType()">type1<br />
<input type="checkbox" class="second" rel="type2" onclick="passType()">type2<br />
<input type="checkbox" class="second" rel="type3" onclick="passType()">type3<br />
<br><br><br>
<div id="result"> </div>
</body>
I am able to get the value in the div "result" thru the following script :
if(isset($_POST['list']) && !isset($_POST['type'])) {
foreach ($_POST['list'] as $list) {
echo "this is $list<br />";
}
}
else if(!isset($_POST['list']) && isset($_POST['type'])) {
foreach ($_POST['type'] as $type) {
echo "type is : $type<br />";
}
}
else if(isset($_POST['list']) && isset($_POST['type'])) {
foreach ($_POST['list'] as $list) {
echo "Showing ads for $list<br />";
foreach ($_POST['type'] as $type) {
echo "type is : $type<br />";
}
}
}
But i get the value of either the list or the type.
I want to be able to get the value of both at the same time. I dont want to use a .
Please help.
Thank you.
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;
}
I have a table with records from a database which is dynamically filled.
<table>
<tr>
<td>name
</td>
<td>surname
</td>
...
</tr>
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['Name'];?>
</td>
<td><?php echo $row_Recordset1['Surname'];?>
</td>
...
<td align="center">
<form name="form" action="novi.php">
<input name="check" type="radio" value="da">Да
<input name="check" type="radio" value="ne">Не
<input type="hidden" id="id" value="<?php echo $row_Recordset1['id_korisnici'];?>">
<input class="button1"type="button" id="klik" value="Испрати"/>
</form>
</td>
</tr>
<?php } while($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</table>
And than I'm using J Query to create an AJAX call to another page which will run the query.
<script>
$('#klik').click(function() {
var check = $("input[name='check']:checked").val();
var id = $('#id').val();
if (check == "da")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik').prop('value', (data));
document.location.reload();
});
}
else if (check == "ne")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik').prop('value', (data));
document.location.reload();
});
}
else
{
$('#klik').prop('value', 'Грешка');
setTimeout("$('#klik').prop('value', '.')",500);
setTimeout("$('#klik').prop('value', '..')",1000);
setTimeout("$('#klik').prop('value', '...')",1500);
setTimeout("$('#klik').prop('value', 'Испрати')",2000);
}
});
This is working OK if there is only one row in the table.
What I don't know how to do is, to make the script store all the generated CHECKED radio buttons in an array or something, plus all the ID's of the records from the database and send them to another page where according to their ID's a query will update the database..
<?php
if ($_POST['id'] != NULL) {
if ($_POST['check'] == "da") {
$id = mysql_real_escape_string($_POST['id']);
$update = mysql_query("update korisnici set validacija = 1 where id_korisnici= '$id'");
if ($update === true) {
echo 'OK';
}else if ($update === false){
echo 'Error!!!';
}
}
elseif ($_POST['check'] == "ne")
{
$id = mysql_real_escape_string($_POST['id']);
$update = mysql_query("update korisnici set validacija = 2 where id_korisnici= '$id'");
if ($update === true) {
echo 'OK';
}
else if ($update === false){
echo 'Error!!!';
}
}
} else {
echo 'Error!!!';
}
?>
Thanks!
P.S. I'm a noob in JQuery and a beginner in PHP...
UPDATE:
I did change some things. And now the values are shown as I want, when I click the button without a selection I'm getting the error message in the ELSE part of the JQuery code in the proper button. But no matter which button I click (if the table is populated with 3 records from the database, there are 3 buttons) only the first row from the table is updated in the database.
<form name="form" action="novi.php">
<input name="check<?php echo $row_Recordset1['id_korisnici'];?>" type="radio" value="da">Да
<input name="check<?php echo $row_Recordset1['id_korisnici'];?>" type="radio" value="ne">Не
<input type="hidden" id="id" value="<?php echo $row_Recordset1['id_korisnici'];?>">
<input class="button1"type="button" id="klik<?php echo $row_Recordset1['id_korisnici'];?>" value="Испрати"/>
</form>
The JQuery:
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').click(function() {
var check = $("input[name='check<?php echo $row_Recordset1['id_korisnici'];?>']:checked").val();
var id = $('#id').val();
if (check == "da")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', (data));
document.location.reload();
});
}
else if (check == "ne")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', (data));
document.location.reload();
});
}
else
{
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', 'Error');
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '.')",500);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '..')",1000);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '...')",1500);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', 'Send')",2000);
}
});
Make each group of radio buttons have a unique name but the same class. Then you can iterate through them using jQuery:
var radioVals = new Array();
var i = 0;
$(".radioButtonClass:checked").each(function() {
radioVals[i] = $(this).val();
});
Then just pass the array in your ajax call.