thanks for being so supportive to the topics asked. I have a built a 'User Approval' system wherein the admin gets list of registered users and approves them by using checkboxes for each and 'Check all' that selects all users. Table has pagination of 10 users at once. My issue here is when I 'check all' on the second page with 10 users, the table automatically selects and displays the first 10 users also i.e. the first page with 10 users. How can I stop the page to second list only when "check all" is implemented on second list of 10 candidates. I am confused on where it has gone wrong and getting no clue . Any help or advice will be appreciated and helpful. Here is the code for javascript that I have used,
<script type="text/javascript">
var select_all = document.getElementById("select_all"); //select all checkbox
var checkboxes = document.getElementsByClassName("checkbox"); //checkbox items
//select all checkboxes
select_all.addEventListener("change", function(e){
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = select_all.checked;
}
});
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function(e){ //".checkbox" change
//uncheck "select all", if one of the listed checkbox item is unchecked
if(this.checked == false){
select_all.checked = false;
}
//check "select all" if all checkbox items are checked
if(document.querySelectorAll('.checkbox:checked').length == checkboxes.length){
select_all.checked = true;
}
});
}
</script>
And the php+html for the table header "Check all"
<input type="checkbox" id="select_all" name="all_check[]" <?php echo $disabled ;?> class="checkbox" value= "<?php //echo $row['id']; ?>"> </th>
And my pagination class,
<?php
class pagination
{
var $page = 1; // Current Page
var $perPage = 10; // Items on each page, defaulted to 10
var $showFirstAndLast = false; // if you would like the first and last page options.
function generate($array, $perPage = 10)
{
// Assign the items per page variable
if (!empty($perPage))
$this->perPage = $perPage;
// Assign the page variable
if (!empty($_GET['page'])) {
$this->page = $_GET['page']; // using the get method
} else {
$this->page = 1; // if we don't have a page number then assume we are on the first page
}
// Take the length of the array
$this->length = count($array);
// Get the number of pages
$this->pages = ceil($this->length / $this->perPage);
// Calculate the starting point
$this->start = ceil(($this->page - 1) * $this->perPage);
// Return the part of the array we have requested
return array_slice($array, $this->start, $this->perPage);
}
function links()
{
// Initiate the links array
$plinks = array();
$links = array();
$slinks = array();
// Concatenate the get variables to add to the page numbering string
if (count($_GET)) {
$queryURL = '';
foreach ($_GET as $key => $value) {
if ($key != 'page') {
$queryURL .= '&'.$key.'='.$value;
}
}
}
// If we have more then one pages
if (($this->pages) > 1)
{
// Assign the 'previous page' link into the array if we are not on the first page
if ($this->page != 1) {
if ($this->showFirstAndLast) {
$plinks[] = ' «« First ';
}
$plinks[] = ' « Prev ';
}
// Assign all the page numbers & links to the array
for ($j = 1; $j < ($this->pages + 1); $j++) {
if ($this->page == $j) {
$links[] = ' <a style="font-weight: bold;">'.$j.'</a> '; // If we are on the same page as the current item
} else {
$links[] = ' '.$j.' '; // add the link to the array
}
}
// Assign the 'next page' if we are not on the last page
if ($this->page < $this->pages) {
$slinks[] = ' Next » ';
if ($this->showFirstAndLast) {
$slinks[] = ' Last »» ';
}
}
// Push the array into a string using any some glue
return implode(' ', $plinks).implode($this->implodeBy, $links).implode(' ', $slinks);
}
return;
}
}
?>
Related
Section 1
I have an issue in " Displaying 1 - 5 of 10 records ". I have a piece of code which works only on first page, when i click on second page then it show the same result " Displaying 1 - 5 of 10 records " Instead of " Displaying 10 of 10 records ".
Code In Controller
$total=$config["total_rows"];
$per_page=$config['per_page'];
$curpage=floor(($this->uri->segment(1)/$config['per_page']) + 1);
$result_start = ($curpage - 1) * $per_page + 1;
if ($result_start == 0) $result_start= 1; // *it happens only for the first run*
$result_end = $result_start+$per_page-1;
if ($result_end < $per_page) // happens when records less than per page
{ $result_end = $per_page; }
else if ($result_end > $total) // happens when result end is greater than total records
{ $result_end = $total;}
$data['show']="displaying $result_start to $result_end of $total";
I don't know whats wrong with it, I have tried other code which I find from different websites, but they are not working properly.
Section 2
I have a filter section, where user can filter product by Size, Color and Price,
How to achieve this section?
My main/ Index Controller
public function index($page=1)
{
$config = array();
$keyword = $this->input->post('search');
if ($keyword === null){ $keyword = $this->session->userdata('search');}
else{ $this->session->set_userdata('search',$keyword);}
$config["base_url"] = base_url();
$config["total_rows"] = $this->crt->total_items($keyword);
$config['use_page_numbers'] =true;
$config['cur_tag_open'] = '<a class="page-numbers current">';
$config['cur_tag_close'] = '</a>';
$config["per_page"] =5;
$config["uri_segment"] = 1;
$this->pagination->initialize($config);
$page = ($page - 1) * $config['per_page'];
// showing x to y of z records
$total=$config["total_rows"];
$per_page=$config['per_page'];
$curpage=floor(($this->uri->segment(1)/$config['per_page']) + 1);
$result_start = ($curpage - 1) * $per_page + 1;
if ($result_start == 0) $result_start= 1; // *it happens only for the first run*
$result_end = $result_start+$per_page-1;
if ($result_end < $per_page) // happens when records less than per page
{ $result_end = $per_page; }
else if ($result_end > $total) // happens when result end is greater than total records
{ $result_end = $total;}
$data['show']="displaying $result_start to $result_end of $total";
$data['sidebar']=$this->crt->sidebar_cat();
$data['products']=$this->crt->get_product($config["per_page"], $page,$keyword);
$data["links"] = $this->pagination->create_links();
$this->load->view('header');
$this->load->view('index',$data);
$this->load->view('footer');
}
My Model
// Paginitions for Items
function total_items($keyword)
{
//return $this->db->count_all("product");
$this->db->like('product_name',$keyword);
$this->db->from('product');
return $this->db->count_all_results();
}
//Fetching Products
public function get_product($limit,$start,$keyword){
// $this->db->where('Is_Hidden',0);
// $this->db->select('*');
// $this->db->from('product');
$this->db->order_by('product_id', 'DESC');
$this->db->limit($limit, $start);
$this->db->like('product_name',$keyword);
$query = $this->db->get_where('product');
if(!$query->num_rows()>0)
{
echo '<h1>No product available</h1>';
}
else
{
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
}
How I can get the Filter section?
UPDATE 1
Section 1 issue has been fixed by replacing those two lines
$curpage=floor(($this->uri->segment(1)/$config['per_page']) + 1);
if ($result_start == 0) $result_start= 1; //
TO
$curpage=$this->uri->segment(1);
if ($result_start == 0 || $result_start<0) $result_start= 1; //
Update 2
I somehow did the filter section but now I am stuck in the ajax issue. Issue is that When color or size checkbox is empty then it throw error of foreach loop.
I only need to control the empty or null section, like if the checkbox is unchecked then it will not send / post the value to the controller...
My Ajax Code is
function clr(){
var selected = new Array();
var size = new Array();
var url="<?php echo base_url('Cart/filt_color');?>";
// alert(url);
$("input:checkbox[name=color]:checked").each(function() {
selected.push($(this).val());
//console.log(selected);
});
// Sizes
$("input:checkbox[name=size]:checked").each(function() {
size.push($(this).val());
//console.log(selected);
});
$.ajax({
url:url,
method:"post",
data:{'colors':selected,'sizes':size},
success:function(data)
{
//
//console.log(data);
$("#mdv").html(data);
}
});
}
I have tried many check like, undefined, or =='' or data.length <-1 etc. The data.length will did some check but i am not able to check the variable separately like, there are two variable I am send in data: color,size How can I check the variable separately like: if(data.color.length < 0 ) .
When you initialize the pagination config try to use the the controller/method in $config[base_url] and get the page number from $this->uri->segment(3)
Answered is Here, All the details and code are posted in the mentioned link question.
Scenario: User votes via HTML form for a field trip to take on a bus. There are three options:
<select id="selectbox">
<option>Berlin</option>
<option>Munich</option>
<option>Cologne</option>
</select>
The free bus seats are stored in / read from a database: ($tour is our array keeping the free seats)
<table class="status">
<tr><td>Berlin: <span id="t1">available (<?php echo $tour[0]; ?> seats)</span></td></tr>
<tr><td>Munich: <span id="t2">available (<?php echo $tour[1]; ?> seats)</span></td></tr>
<tr><td>Cologne: <span id="t3">available (<?php echo $tour[2]; ?> seats)</span></td></tr>
</table>
If free seats are zero, we display a "sorry, booked out" info using vanilla JavaScript:
// get content of status table
var t1 = document.getElementById("t1").innerHTML;
var t2 = document.getElementById("t2").innerHTML;
var t3 = document.getElementById("t3").innerHTML;
var bookedout = "sorry, booked out!"
// check if condition is met
if (t1 == "available (0 seats)") {
document.getElementById("t1").innerHTML = bookedout;
}
if (t2 == "available (0 seats)") {
document.getElementById("t2").innerHTML = bookedout ;
}
if (t3 == "available (0 seats)") {
document.getElementById("t3").innerHTML = bookedout ;
}
Works fine. However, now comes the part I'm a bit lost. The above condition should also delete the respective option from #selectbox based on the option's innerHTML. In jQuery I'd go with something like #selectbox option:contains('stringhere').
However, I wanna do it in the purest of JavaScript. Any ideas?
It's fairly straight forward..
First in your html give vlaues to your options:
<select id="selectbox">
<option>Berlin</option>
<option>Munich</option>
<option>Cologne</option>
</select>
Then in js:
var mySelect = document.getElementById("selectbox");
//function to get option values as array
function getOptionsArr() {
var optionsArray =[],options = mySelect.options;
var i = 0, len = options.length;
// store the options value in an array
while (i < len)
{
optionsArray.push(options[i++].value);
}
return optionsArray;
}
var t1 = document.getElementById("t1").innerHTML;
var t2 = document.getElementById("t2").innerHTML;
var t3 = document.getElementById("t3").innerHTML;
var bookedout = "sorry, booked out!"
// check if condition is met
if (t1 == "available (0 seats)"){
document.getElementById("t1").innerHTML = bookedout;
//this will get the whole parent node and child node inner text we split at : and get the value
var textArr = document.getElementById("t1").parentElement.innerText.split(':');
// find the index of value from our array created above and remove that option from select
mySelect.remove(getOptionsArr().indexOf(textArr [0]))
}
//repeat the same for other
if (t2 == "available (0 seats)"){
document.getElementById("t2").innerHTML = bookedout ;
var textArr = document.getElementById("t2").parentElement.innerText.split(':');
mySelect.remove(getOptionsArr().indexOf(textArr [0]))
}
if (t3 == "available (0 seats)"){
document.getElementById("t3").innerHTML = bookedout ;
var textArr = document.getElementById("t3").parentElement.innerText.split(':');
mySelect.remove(getOptionsArr().indexOf(textArr [0]))
}
Aditionally you can refactor it by
var mySelect = document.getElementById("selectbox");
//function to get option values as array
function getOptionsArr() {
var optionsArray =[],options = mySelect.options;
var i = 0, len = options.length;
// store the options value in an array
while (i < len)
{
optionsArray.push(options[i++].value);
}
return optionsArray;
}
var t1 = document.getElementById("t1").innerHTML;
var t2 = document.getElementById("t2").innerHTML;
var t3 = document.getElementById("t3").innerHTML;
var bookedout = "sorry, booked out!"
// check if condition is met
if (t1 == "available (0 seats)"){
doUpdateDOM("t1")
}
if (t2 == "available (0 seats)"){
doUpdateDOM("t2")
}
if (t3 == "available (0 seats)"){
doUpdateDOM("t3")
}
function doUpdateDOM(nodeID){
document.getElementById(nodeID).innerHTML = bookedout;
var textArr = document.getElementById(nodeID).parentElement.innerText.split(':');
mySelect.remove(optionsArray.indexOf(textArr [0]))
}
Assuming that the order of the options inside the select correspond to the order inside the table element you could simply do something like this.
var select = document.getElementById('selectbox');
var table = document.getElementsByClassName('status').item(0);
var rows = table.rows;
var bookedout = " sorry, booked out!";
// check whether an option is bookedout
// and save its state to a new array.
var bookedOutState = [].slice.call(rows).map(function(row) {
var match = row.children[0].textContent.match(/\d/);
if (+match[0] === 0) {
row.children[0].textContent = match['input'].substr(0, match['input'].indexOf(':') + 1) + bookedout;
return false;
}
return true;
})
// go over the new created array and remove
// options from select according to the saved state.
bookedOutState.forEach(function(state, idx) {
if (!state) {
select.removeChild(select.children[idx])
}
})
<select id="selectbox">
<option>Berlin</option>
<option>Munich</option>
<option>Cologne</option>
</select>
<table class="status">
<tr><td>Berlin: <span id="t1">available 0 seats</span></td></tr>
<tr><td>Munich: <span id="t2">available 1 seats</span></td></tr>
<tr><td>Cologne: <span id="t3">available 2 seats</span></td></tr>
</table>
How can I refresh second select option when first select option is changed?
I am generating the array here for patient_code2:
//GENERATE NUMBERS FOR CYCLE
function patsient(selector) {
var i;
for (i = 1; i <= 99; i++) {
var text = '0' + i;
selector.options[i - 1] = new Option(text.substr(text.length - 2, 2));
}
}
patsient(document.getElementById("patient_code2"));
I am generating the array for patient_code here:
function myFunction(selector) {
var i;
for (i = 1; i <= 999; i++) {
var text = '00' + i;
selector.options[i - 1] = new Option(text.substr(text.length - 3, 3));
}
}
//usage:
myFunction(document.getElementById("patient_code"));
Here I am inserting the last value from database to the field:
//INSERT THE VALUE FROM DATABASE
var tsykkel_id = '<?php foreach ($tsykkel_id as $row){echo $row['patsiendi_tsykkel'];}?>';
$('#patient_code2')[0].options[parseInt(tsykkel_id)].selected = true;
$(document).ready().on('change', '#patient_code2', function () {
var index = $('option:selected', $(this)).index();
$('option', $(this)).each(function (i, x) {
if (i < index) { $(this).remove(); }
});
});
HTML
<select name="patient_code" data-placeholder="" id="patient_code" class="chosen-select form-control" tabindex="2">
</select>
<label class="control-label">Tsükkel:</label>
<select name="patient_code2" data-placeholder="" id="patient_code2" class="chosen-select form-control" tabindex="2">
</select>
So lets say that person chooses 002 from the first then the second should start from 01 again.
try this then. Code is tested.
$(document).ready().on('change','#patient_code2',function(){
var index = $('option:selected',$(this)).index();
$('option',$(this)).each(function(i,x){
if(i<index){$(this).remove();}
});
$('select#patient_code').prop('selectedIndex', 0);
});
fiddle : http://jsfiddle.net/roullie666/69j94ro6/2/
You can just start printing after the match has been found. I am writing both ways since you asked?
For javascript version use roullie's no point duplicating.
<?php
$flag = false;
foreach ($tsykkel_id as $row) {
if ($selected) {
$flag = true;
}
if ($flag) {
$row['patsiendi_tsykkel'];
}
}?>
I have problem when a visitor clicks on a submenu and the link opens in a new page, so I want to keep that submenu active on that page.
I have css class active and javascript for opening it, what I need is to make it with php to be active.
This is UL with class:
This is my code. Can it be done with php or with javascript.
<ul>
<?php
$qKategori = ("SELECT * FROM kategori WHERE kprind = 0");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){
$emrikategorise = $exKat['kemri'];
$idkategori = $exKat['kid'];
$idprind = $exKat['kprind'];
?>
<li><?=$emrikategorise;?>
<ul>
<?php
$qPrind = ("SELECT * FROM kategori WHERE kprind = '".$idkategori."'");
$rPrind = mysqli_query($dbc,$qPrind);
while($prind = mysqli_fetch_array($rPrind)) {
?>
<li><?=$prind['kemri']?> </li>
<?php
}
mysqli_free_result($rPrind);
?>
</ul>
</li>
<?php }
mysqli_free_result($rKategori);
}
?>
</ul>
You can see menu on the left in The website is www.sitimobil.mk
You probably will need to build the array before outputting to be able to determine which menus should be active. You can also combine it with an optimization of the query to not have to do 1 query per category.
Something like:
$active = isset($_GET['kid'] ? $_GET['kid'] : -1;
$tree = array();
$list = array();
$qKategori = ("SELECT * FROM kategori ORDER BY kprind");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){
$id = $exKat['kid'];
//To prevent numerical array with unused space
$name = 'kategori'.$exKat['kid'];
$list[$name] = $exKat;
//Calculate depth to see if the menu is a sub..sub..sub menu etc.
$parent = $list[$name]['kprind'];
if($parent == 0) {
$list[$name]['depth'] = 0;
$list[$name]['childCount'] = 0;
}
else {
$list['kategori'.$parent]['childCount']++;
$list[$name]['depth'] = $list['kategori'.$parent]['depth']+1; //Increment
}
if($id == $active) {
$list[$name]['active'] = true;
while($parent != 0) {
$parentName = 'kategori'.$parent;
$list[$parentName]['active'] = true;
$parent = $list[$parentName]['kprind'];
}
}
else
$list[$name]['active'] = false;
}
mysqli_free_result($rPrind);
//Once we have that we can output the results...
function output_menu($list, $parent = 0, $active = false)
$activeClass = $active ? ' class="active"' : '';
echo '<ul'.$activeClass.'>';
foreach($list as $row){
if($row['kprind'] != $parent) continue;
$link = $row['kprind'] == 0 ? '#' : 'kategori.php?kid='.$row['kid'];
echo '<li>'.$row['kemri'].'';
if($row['childCount'] > 0)
output_menu($list, $row['kprind'], $row['active']);
echo '</li>';
}
echo '</ul>';
}
output_menu($list);
}
This is still a bit rough but should do the trick. It can probably be optimized so that we don't have to go through the list too many times but has the benefit of not having to request too many calls to the database. That should result in a lighter workload for the DB and faster output.
I have an html form in with a drop down menu and a series of checkboxes. The dropdown has two options. Each option is supposed to check several of the checkboxes using javascript with an onchange event within the "select" tag. This works 100%, but it fails when I trigger it with more javascript.
I have narrowed it down to the part where is resets all the checkboxes to be unchecked. It is then supposed to select the boxes it needs based on the drop down, but because it fails to uncheck them all, they all remain checked.
Here is the code:
select box:
<select name='myrp_autogroups' id='myrp_autogroups' onchange='myrp_group_selector();'>
<option></option>
<?php
$presets = get_option("myrp_presets");
for ($i = 0; $i < count($presets); $i++) {
$preset = $presets[$i];
echo "<option value='";
for ($b = 0; $b < count($preset[1]); $b++) {
$checkbox = $preset[1][$b];
echo $checkbox . ",";
}
echo "'";
echo ">" . $preset[0] . "</option>";
}
update_option("myrp_presets", $presets);
?>
</select>
<input type="button" value="change" onclick="change_group();">
<script type='text/javascript'>
window.onload = change_group();
</script>
Javascript:
function myrp_group_selector()
{
// reset everything.
$mrjQ(".myrp_checkboxes").each(function() {
var name = this.id.split("myrp_c_");
if(name.length == 2) {
document.getElementById("myrp_value_" + name[1]).disabled=true;
document.getElementById("myrp_value_" + name[1]).value="";
this.checked=false;
}
});
if(document.getElementById("myrp_average_top") != null)
{
document.getElementById("myrp_average_top").checked=false;
document.getElementById("myrp_average_value_top").value="";
}
if(document.getElementById("myrp_average_bottom") != null)
{
document.getElementById("myrp_average_value_bottom").value="";
document.getElementById("myrp_average_bottom").checked=false;
}
var checkThese = document.getElementById("myrp_autogroups")[document.getElementById("myrp_autogroups").selectedIndex].value;
var checkArray = checkThese.split(",");
var average = "avg";
// check the new stuff
for(var i in checkArray)
{
if(checkArray[i] == average)
{
if(document.getElementById("myrp_average_top") != null)
{
document.getElementById("myrp_average_top").checked=true;
}
if(document.getElementById("myrp_average_bottom") != null)
{
document.getElementById("myrp_average_bottom").checked=true;
}
}
else
{
document.getElementById("myrp_c_"+checkArray[i]).checked=true;
document.getElementById("myrp_value_"+checkArray[i]).disabled=false;
}
}
}
function change_group() {
select = document.getElementById('myrp_autogroups');
if(select.value != '2,3,4,5,6,'){
select.value = '2,3,4,5,6,';
select.onchange();
}
}
I have narrowed it down to this section, keep in mind it functions perfectly if i manually select an option from the dropdown and doesn't work when triggered by java:
// reset everything.
$mrjQ(".myrp_checkboxes").each(function() {
var name = this.id.split("myrp_c_");
if(name.length == 2) {
document.getElementById("myrp_value_" + name[1]).disabled=true;
document.getElementById("myrp_value_" + name[1]).value="";
this.checked=false;
}
});
the wrong is :
window.onload = change_group() ;
it should be
window.onload = change_group;