Maximum three checkbox selected and other disable - php

I'm working on a project and made a grid on admin side in which all projects are shown so that when admin click on three projects they should be shown on index page of that site and makes other check boxes disable after selecting three projects and when to change it remove one of selected check box and then give selection to others.what I did is got a java script code from stack overflow.Now this code is working but problem is that when i refresh page or navigate from other menu more check boxes could be selected even it shows the previous three selected projects on index page.how can i make it to not select after page refresh. here is code
function disableHandler (form, inputName) {
var inputs = form.elements[inputName];
for (var i = 2; i < inputs.length; i++) {
var input = inputs[i];
input.onclick = function (evt) {
if (this.checked) {
disableInputs(this, inputs);
}
else {
enableInputs(this, inputs);
}
return true;
};
}
}
function disableInputs (input, inputs) {
for (var i = 2; i < inputs.length; i++) {
var currentInput = inputs[i];
if (currentInput != input) {
currentInput.disabled = true;
}
}
}
function enableInputs (input, inputs) {
for (var i = 2; i < inputs.length; i++) {
var currentInput = inputs[i];
if (currentInput != input) {
currentInput.disabled = false;
}
}
}

You should persist selection in a database. Here's a to-do list:
After each selection/deselection, send a background ajax request to the server, with details of selected checkbox(es).
On the server save this information to the database.
When user refreshes page, use information from the database to render checked checkboxes as checked, and others as disabled.

You could send an ajax request to set the session variables to keep track of what a user has selected.
Something like $_SESSION['checkbox']['opt1']=1 for if that particular item is checked
I don't quite follow what you are trying to do though, but it seems relatively simple. Let me know if you need more help.

Related

Hot to get all the images to display without reloading the page in PHP?

After User Clicks Sumbit Button Data passes through one half of the path to images and then the code below links it to the second half. I want to know how I can display all this without Page Reload? I know it might be done with AJAX but I have no idea on how to do so. So please can someone help?
<?php
$albumnamepath = $_POST['field'];
echo $albumnamepath;
$display = "SELECT * FROM paths WHERE user_id = '$session_user_id' AND album_name = '$albumnamepath'";
$result = mysql_query($display);
echo "<table>";
$i = 0;
while ( $row = mysql_fetch_array($result) ) {
if ($i % 4 == 0) { //3 == 0.
echo '<tr>';
}
echo "<td>".'
<ul class="img-list">
<li><div class="picbox"><img src="'.$albumnamepath.$row['thumbnail'].'"><span class="text-content"><span>'.$row['caption'].'</span></span>'."</li>
</ul>
</td>";
//echo '<a href="'.$albumnamepath.$row['location'].'" class="swipebox" title="'.$row['caption'].'"><img src="'.$albumnamepath.$row['thumbnail'].'">';
if ($i % 4 == 3) { //3 == 2.
echo '</tr>';
}
$i++;
}
//Here is a check in case there is not a multiple of 3 images in a row.
if ($i % 4 != 0) { //4 != 0.
echo '</tr>';
}
echo "</table>";
?>
Thank you.
I don't think Ajax would help you very much, since you'll be using ajax to get, essentially, the entire page. Ajax is usually used if you want to change a part of the page, and the data either has to come from the server real-time (i.e. after the page is loaded), or is expensive to calculate or deliver in full (e.g. a very long, or infinite list, and if most users only use a small amount). Otherwise, it's more efficient to send all the data in one go, and then manipulate it in the browser.
I would suggest the following approach: divide the table rows into groups of table rows; e.g. 5 rows (chosen arbitrarily). Change the block of code where you echo '' to:
if ($i % 4 == 0) { //3 == 0.
$block=ceil($i/(4*5));
echo '<tr class="block_$block">';
}
This means each block of 5 rows (by 4 across) will be a different class - "block_1", "block_2" and so forth.
Then, you can hide and display blocks using Javascript. To hide a block, use the following javascript code:
var trToHide = document.getElementsByClassName("block_1");
for(var i = 0; i < trToHide.length; i++) {
trToHide[i].style.display="none";
}
To unhide a block:
var trToHide = document.getElementsByClassName("block_3");
for(var i = 0; i < trToHide.length; i++) {
trToHide[i].style.display="block";
}
Obviously, you will want to use variables to keep track of which block is displayed; then you can have a "Next" and "Back" button, which hides the current block, adds/subtracts one, then displays the (new) current block. You will also want to have all blocks except the first one hidden at the start. Left as an exercise to the reader.
Answer:
You have to use ajax request.
You use form to set filters? Then you can use .ajaxSumbit (but you need jQuery Form Plugin for it).
Also, you can add form submit handler, where you will prevent form default submit action and send ajax request instead of it. Look this example:
File getImages.php:
// in this file you will do same actions as you do now to output table with images
Note, that getImages.php must contain only table with results or message, that there are no results.
File with form, where you set filters:
// some html with forms etc
<form id='myForm'>
// some inputs etc
</form>
<div id='results'></div>
And javascript:
$("#myForm").submit(function(e) { // use e parameter for preventDefault();
$.ajax({
type: "POST",
url: "path/to/getImages.php",
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(data)
{
$("#results").html(data);
}
});
return false; // <-- deny sumitting from and reloading page
//e.preventDefault(); // <-- this do same as `return false;` <-- deny sumitting from and reloading page
});
Explanation:
Browser load page with form, where you can set filters. User sets filters and pressing button submit. Browser will send ajax request to file getImages.php with some parameters (filters, user set filter before sending the form). This script generates some output with table, with img tags etc and return it. Browser receives this output and puts it to element with id #results:
<div id='results'></div>
^
------------------^
Data, generated by script getImages.php will be inserted here.
So, filtered images will be received and shown without page reload :)
Is it what you need?
Hope this will help you.

JS checkbox.checked vs manually checking

I have a page which is paginated to 100 results per page by php with checkboxes beside each. I have three functions: one to select all, one to save what was checked, and one to restore what was checked.
I don't understand why my toggle function does not work with the other two.
If I click select all (which performs a toggle()) the checked values are not saved;
however, if I click them by hand they do get saved across pagination.
I am assuming that I have to do something along the lines of persistCheckBox(checkboxes[i].checked) to the last line of my toggle function --which I tried and it did not work; Can someone explain why?
function toggle(source) {
checkboxes = document.getElementsByName('multi_mag[]');
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
function restorePersistedCheckBoxes() {
var aStatus = getPersistedCheckStatus();
for (var i = 0; i < aStatus.length; i++) {
var aPair = aStatus[i].split(':');
var el = document.getElementById(aPair[0]);
if (el) {
el.checked = aPair[1] == '1';
}
}
}
function persistCheckBox(el) {
var found = false;
var currentStateFragment = el.id + ':' + (el.checked ? '1' : '0');
var aStatus = getPersistedCheckStatus();
for (var i = 0; i < aStatus.length; i++) {
var aPair = aStatus[i].split(':');
if (aPair[0] == el.id) {
// State for this checkbox was already present; replace it
aStatus[i] = currentStateFragment;
found = true;
break;
}
}
if (!found) {
// State for this checkbox wasn't present; add it
aStatus.push(currentStateFragment);
}
// Now that the array has our info stored, persist it
setPersistedCheckStatus(aStatus);
}
Neither the click nor the change events are triggered when changing the checked value programmatically.
Since you tagged your question with jQuery, I will demonstrate using some jQuery code.
It is unclear from your code how you do your persistent storage or what is your HTML structure, so the code will show a general approach.
A word of advice, though: I strongly suggest that you remove styling code out of the structure and use CSS and avoid inline event handling. Pretty much everything that you want to accomplished can be done more cleanly from outside the HTML.
I will be suing a form with several checkboxes, the first of which will change the other checkboxes' state.
HTML:
<form id="boxes">
<input type="checkbox" id="all" name="all" />
<input type="checkbox" name="multi_mag[]" class="normal" />
...
<input type="checkbox" name="multi_mag[]" class="normal" />
</form>
Javascript:
In this example, all of the 'normal' checkboxes have some common property (in this case, I decided on a class), that allow event delegation.
$('#boxes').delegate('.normal', 'change', function (e) {
console.log('changed', e.target.checked);
});
This code sets a function to run every time a checkbox changes, corresponding to your persistCheckBox() method.
Next, the equivalent of your toggle() function:
$('#all').change(function (e) {
var checked = e.target.checked;
console.log('changed checkall box: ', checked);
checkboxes = document.getElementsByName('multi_mag[]');
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = checked;
$(checkboxes[i]).change();
}
});
It is executed whenever the "main" checbox changes its state. All of the checkboxes are iterated, their values are changed and the change event is triggered, which causes each to run the aforementioned function.
You can apply this method to your (cleaned) code, and the persistence should be maintained.
Example jsFiddle (check your console for the activity log).
This little piece of code can check / uncheck a checkbox, and will trigger any associated events.
$('input[type=checkbox]').trigger('click');
It could help maybe
I fixed this by adding I fixed this by adding "persistCheckBox(checkboxes[i]);" to the last line of the toggle() function. #MasterAM I appreciate your critiques and will be using them to optimize my code. I also appreciate the JQuery solution you provided.

javascript function to validate radio buttons giving strange output.

I'm developing a quiz that pulls data out of a mysql database, and displays the results as radio buttons. The radio buttons are populated based off of key=>value and generated via a simple forloop. This has been done many times, simple google searching and research will yield all the results needed to accomplish this. The issue that I'm having, or was having (before I decided to just do this with jquery) was when I submit the form it would execute the javascript function to validate whether a button has been selected, but when you select any option other than the first radio button you'd receive the same "make a selection" alert that you would if you had not selected any buttons. Selecting the first radio button would return true and execute the getCheckedValue function call. It seems as though, the script only recognizes that I have one input type and doesn't understand to iterate through the rest of the buttons. I've refactored this function a dozen times, and still have no idea why this doesn't work.
<?php
foreach ($dataReturn as $j => $value){
echo "<input type='radio' class='answer' id='radiobtn' name='radiobtn' value='".$j."'>" .$value." </input><br/>";
}
?>
Above is the loop that generates the radio buttons (just for reference, $dataReturn is the return value of a shuffled associative array. (Which is working as intended)
When the submit button is clicked, it calls the below javascript function.
function isNull(){
var isChecked = false;
var radiobutton = document.getElementsByName('radiobtn');
for (var i=0; i <= radiobutton.length; i++){
if (radiobutton[i].checked){
return true;
var answer = radiobutton[i].value;
getCheckedValue(answer);//using this just for testing selected value
}else {
alert("Make a selection.");
}
return false;
}
}
I just can't figure out why this doesn't work. As stated above, using jquery this works perfectly.
Your FOR loop: since JS uses zero-based arrays, you can't have <=, otherwise it will look for an index one higher than what you have. Use < instead;
I moved your validation for whether any fields were checked outside the loop to make management easier. It's cleaner this way than worrying about breakout out of loops in the middle of them.
Here:
function isNull() {
var isChecked = false;
var radiobutton = document.getElementsByName('radiobtn');
for (var i=0; i < radiobutton.length; i++) {
if (radiobutton[i].checked) {
isChecked = true;
}
}
if ( !isChecked ) {
alert("Make a selection.");
return false;
}
}
I don't know how your form tag looks, but here is what you need to prevent the form from submitting if no radio fields are checked:
<form action="" method="post" onSubmit="return isNull();">
Try the code below. You do not want your alert to fire or return false until after the for loop is finished.
function isNull(){
var isChecked = false;
var radiobutton = document.getElementsByName('radiobtn');
for (var i=0; i <= radiobutton.length; i++){
if (radiobutton[i].checked){
var answer = radiobutton[i].value;
getCheckedValue(answer);//using this just for testing selected value
return true;
}
}
alert("Make a selection.");
return false;
}
Also, your php code gives all radio buttons the same id. That is bad; doing so violates w3c standards.

Populate Select list Menu though Ajax Jquery

Before anybody says this is a duplicate of this and that question, let me assure you I have tried the solutions there and I have failed. I am using a solution offered in this website to come up with my solution and I believe I am 90% done except for one error. I want to display a list of all codes that have a certain common ID associated with them.
Here is my PHP code that I am using to get a list of codes
<?php
$budgetcode=$_POST['budgetcode'];
//$budgetcode=2102;
$selectcodes="SELECT * FROM tblbudget_codes WHERE T1 = $budgetcode";
$query=$connection->query($selectcodes);
$count=$query->num_rows;
if($count < 1)
{
die('0');
}
else{
while($row=$query->fetch_array()){
$T1=($row['T1']);
$T2=($row['T2']);
$T3=($row['T3']);
$T4=($row['T4']);
$optionValue = $T1."-".$T2."-".$T3."-".$T4;
echo json_encode("<option>$optionValue</option");
// echo json_encode('1');
}
}
?>
Here is the ajax call i am using to fetch the codes
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(data!='0')
{
$("#budgetcode").html(data).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
//alert(budgetid);
})
The problem here is that jquery does not understand the data it is receiving if it is not numeric. E.g if I comment out the json_encode('1') and put random html code instead of data in my success part, I get results displayed in my browser. Can anybody tell me why jquery is only recognizing numeric values that are being echoed from PHP and not varchar values. Using jquery 1.4.2. Any help appreciated.
EDIT
I have managed upto some point and now i am stuck. I have used John's Answer and here is my jquery code. i just need to split the array and append each element to a variable one at a time like here
here is the code. Somebody please tell how I split (data). i can alert it but it is comma seperated. Just need to get the individual items append them to variable html and then display it.
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(!$.isEmptyObject(data))
{
//alert (data);
// alert(split (data))
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option>' +data+ '</option>';
}
$("#budgetcode").html(html).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
I would skip JSON altogether:
PHP
echo "<option>$optionValue</option>";
Everything else should work.
Finally figured it out. Here is the php code
$selectcodes="SELECT * FROM tblbudget_codes WHERE T1 = $budgetcode";
$query=$connection->query($selectcodes);
$count=$query->num_rows;
if($count < 1)
{
die('0');
}
else{
while($row=$query->fetch_array()){
$data[] = $row;
}
echo json_encode($data);
}
?>
Here is the jquery code
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(!$.isEmptyObject(data))
{
//alert (data);
var html = '';
var joiner='';
var len = data.length;
for (var i = 0; i< len; i++) {
joiner=([data[i].T1,data[i].T2,data[i].T3, data[i].T4].join('-'));
//alert(joiner);
html += '<option>'+joiner+'</option>';
}
$("#budgetcode").html(html).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
Had to use join to join the multiple codes using a dash. Hope this helps. The PHP part and part of the jquery was inspired by this question
FWIW, for populating select lists I usually use the following jQuery code:
// populates select list from array of items given as objects: {
name: 'text', value: 'value' }
function populateSelectList(parent, items) {
parent.options.length = 0;
if (parent.options.length === 0) {
parent.options[0] = new Option("Please select something...", "");
}
$.each(items, function (i) {
if (typeof (this) == 'undefined') { return; }
parent.options[el.options.length] = new Option(this.name, this.value);
});
}
and to call the above function i pass the results of an ajax call using the map method where #select is the selector for the parent select element. I am setting the Text property to the name and Value to the value but that should change according to the objects returned by the ajax call (e.g. assuming the returned objects have a Value and Text properties).
populateSelectList($('#select').get(0), $.map(results, function
(result) { return { name: result.Text, value: result.Value} }));

Get checkboxes on the page with jQuery and put the values into string to send ajax call

What I'm trying to do is use jQuery to grab any checkboxes that are checked on the page. The boxes are dynamically created using a specific ID number of each one for the ID and Value.
What is the easiest way about getting it to grab the values of each checked item? Then check if less than or greater than 3 is checked. If only 3 are checked then send the values of each checkbox to my php script. I'm using a regular button on the page so I will proably have to use the .click method since its not actually part of a form to submit.
I've seen several examples around here but not quite what I'm trying to do.
$('#mybtn').live('click',function(){
$("input[type=checkbox]").each(function() {
// I guess do something here.
)};
)};
the code i believe you are wanting is this
$('#mybtn').live('click',function(){
var num_checked = $("input[type=checkbox]:checked").length;
var checkbox_values = new Array();
if( num_checked > 3 ) {
//its greater than 3
//do what you need to do
} else if( num_checked < 3 ) {
//its less than 3
//do what you need to do
}else {
//it equals 3
//do what you need to do
//go thru and add values to array
$("input[type=checkbox]:checked").each(function() {
checkbox_values.push($(this).val());
});
}
});
if you want to send email of variables you can output array checkbox_values to php
If all your checkboxes are in a form, you can do $('#form_id').serialize();
You can get how many are checked using
$("input[type=checkbox]:checked").length
http://jsfiddle.net/XKRRL/7/
Not really sure what you want to do with the ones that are checked, but the js fiddle loops through the checked ones. From there you could grab id's etc.
full code
$(function() {
$('#mybtn').live('click', function() {
var checkedBoxes = $("input[type=checkbox]:checked"),
checkedNum = checkedBoxes.length;
if(checkedNum === 3){
for(var i=0; i< checkedNum; i++){
alert($(checkedBoxes).eq(i).val());
}
}
});
});
It's simple to grab all checked checkboxes:
var checked = $('input[type=checkbox]:checked'),
count = checked.length;
if (count == 3) {
values = $.map(checked, function(i){
return $(this).val();
});
}
Then do whatever you want on the values array.

Categories