using JavasSript to check checkboxes in PHP form - php

Hi I am trying to add some function which only allows the user to select up to 4 checkboxes at a time, but failing miserably... php and javascript don't seem to be working together very well!
my PHP code is:
<?php
echo "<form method='post' name='time' action='timeinsert.php'>";
echo "<td><input type='checkbox' `name='$displayTime2'onclick='KeepCount()'></td>";
echo "</form>";
?>
my Javascript code is:
<script language="JavaScript">
<!--`
function KeepCount() {
var NewCount = 0
if (document.time.<?php"$displayTime2"?>.checked)
{NewCount = NewCount + 1}
f (NewCount == 4)
{
alert("Pick maximum of 4 time slot's Please")
document.time; return false;`
}
//-->
</script>

Using jQuery:
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'>
</script>
<script type='text/javascript'>
$(function() {
$('input[type=checkbox]').click(function () {
var count = $('input[type=checkbox]:checked').length;
if (count > 4) alert('Pick maximum of 4 time slots please!');
});
});
</script>
<?php
echo "<form method='post' name='time' action='timeinsert.php'>";
echo "<td><input type='checkbox' name='$displayTime2'></td>";
echo "</form>";
?>
UPDATE: To prevent further checks from happening after 4 clicks, you can do this:
<script type='text/javascript'>
$(function() {
$('input[type=checkbox]').click(function () {
var count = $('input[type=checkbox]:checked').length;
if (count > 4) {
$(this).removeAttr('checked');
alert('Pick maximum of 4 time slots please!');
}
});
});
</script>

<script language="JavaScript">
var NewCount = 0;
function KeepCount()
{
if(NewCount <= 4)
{
if (document.time.<?php echo $displayTime2; ?>.checked)
{
NewCount = parseInt(NewCount)+1;
}
}
else
{
alert("Pick maximum of 4 time slot's Please");
return false;
}
}
</script>

Okay I have now edited Stefan's code and come up with:
<script type='text/javascript' src='includes/jquery-1.9.1.min.js'>
</script>
<script type='text/javascript'>
$(function() {
$('input[type=checkbox]').click(function () {
var count = $('input[type=checkbox]:checked').length;
if (count > 4) alert('Pick maximum of 4 time slots please!');
if (count > 4) $(this).removeAttr("checked");
});
});
</script>
this alerts the user and removes and ticks after 4 checkboxes have already been selected. Is it possible to add
$(this).removeAttr("checked");
to the first if statement rather than adding another line of code?

Related

limit selectable checkboxes in an array, (max 1 per column, 10 per row, 15 total) based on three php variables

I have an array of checkboxes generated with php. I can not display every checkbox because of previous choices by other users.
for($i=0;$i<$maxrows;$i++)
{
$already_selected[$i]=0;
for($a=0;$a<$maxcols;$a++)
{
$value=$mat[$i][$a];
if($value>0)
{
echo"<input type='checkbox' name='arr[$i][$a]' value='$uid'/>";
}
else
{
echo"<input type='hidden' name='arr[$i][$a]' value='$value'/>";
$already_selected[$i]+=1;
}
}
}
I have to limit the selectable checkboxes in a (for me, at least) complex way:
The user must be able to choose:
- One checkbox for each column maximum
- Maximum $x checkboxes per row (where x is calculated by php as: $maximum_per_row - $already_selected)
- Maximum $y checkboxes over the entire grid (where y is a php variable received by the previous page).
Is it possible?
Maybe something like:
echo"
<script type='text/javascript'>
var limit = $y;
$('input.ggrid').on('change', function(evt)
{
if($('input[class='ggrid']:checked').length >= limit)
{
this.checked = false;
}
});
</script>
";
for($i=0;$i<$maxrows;$i++)
{
echo"
<script type='text/javascript'>
var limit = $maximum_per_row[$i] - $already_selected[$i];
$('input.row$i').on('change', function(evt)
{
if($('input[class='row$i']:checked').length >= limit)
{
this.checked = false;
}
});
</script>
";
for($a=0;$a<$maxcols;$a++)
{
echo"
<script type='text/javascript'>
var limit = 1;
$('input.col$a').on('change', function(evt)
{
if($('input[class='col$a']:checked').length >= limit)
{
this.checked = false;
}
});
</script>
";
}
}
for($i=0;$i<$maxrows;$i++)
{
$already_selected=0;
for($a=0;$a<$maxcols;$a++)
{
$value=$mat[$i][$a];
if($value>0)
{
echo"<input type='checkbox' class='col$a row$i ggrid'name='arr[$i][$a]' value='$uid'/>";
}
else
{
echo"<input type='hidden' name='arr[$i][$a]' value='$value'/>";
$already_selected+=1;
}
}
}
which obviously does not work...
Thank you in advance!
Please refer to the following code. PHP and pure javascript, no jQuery.
<?php
$maxrows=4; //example, you could replace it with your value
$maxcols=8; //example, you could replace it with your value
$y=1; //example, you could replace it with your value
$x=array();
for($i=0;$i<$maxrows;$i++)
{
$already_selected[$i]=0;
$test_symbol=1; //value to let half of the inputs are hidden for example, you could delete it
for($a=0;$a<$maxcols;$a++)
{
//$value=$mat[$i][$a];
$test_symbol=$test_symbol==1?-1:1;
$value=$a*$test_symbol; //as example, you could replace it with your value
$uid=$a; //as example
if($value>0)
{
echo"<input type='checkbox' id='arr_".$i."_".$a."' name='arr_".$i."_".$a."' value='$uid'/ onclick='check_limit($i,$a)'> \n";
}
else
{
echo"<input type='hidden' name='arr_".$i."_".$a."' value='$value'/> \n";
$already_selected[$i]+=1;
}
}
echo "$i row selected:".$already_selected[$i]."\n <br>";
$x[$i] = $maxcols-$already_selected[$i]-$y;
}
?>
<script language="javascript">
var row_limit = <?php echo json_encode($x) ?>;
var maxrows = <?php echo $maxrows ?>;
var maxcols = <?php echo $maxcols ?>;
function check_limit(row,col){
//row control, max allowd by array calculated from PHP
for(i = 0; i < maxrows; i++){
tempSelected = 0;
for(j=0;j<maxcols;j++){
if(document.getElementById("arr_"+i+"_"+j)){
if(document.getElementById("arr_"+i+"_"+j).checked){
tempSelected++;
}
}
}
if(tempSelected>row_limit[i]){
alert("Maximum " + row_limit[i] + "per row allowed!");
document.getElementById("arr_" + row + "_" + col).checked=false;
return;
}
}
//column control, max 1 allowed for each column
for(j=0;j<maxcols;j++){
tempSelected = 0;
for(i=0;i<maxrows;i++){
if(document.getElementById("arr_"+i+"_"+j)){
if(document.getElementById("arr_"+i+"_"+j).checked){
tempSelected++;
}
}
}
if(tempSelected>1){
alert("Maximum 1 per column allowed!")
document.getElementById("arr_"+row+"_"+col).checked = false;
return;
}
}
}
</script>

In PHP, session variable is not storing the value. What is wrong?

The following is a sample PHP code. I am expecting the session variable 't' to increment its value when update function is called. However, when I run the code I keep getting the output as Value: 1. What should I do so that the value is stored into the session variable?
<?php
session_start();
if(!isset($_SESSION['t'])) {
$_SESSION['t'] = 0;
}
?>
<div id="test" class="test"></div>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
function update() {
var ct = "<?php echo $_SESSION['t'] += 1 ?>";
<?php echo "Value: " . $_SESSION['t']; ?>;
$("#test").html(ct);
}
$(document).ready(function() {
setInterval('update()', 1000);
});
</script>
Put session_start() at the very top of your script, before any output
<?php
session_start();
// if you automatically set SESSION['t'] to 0 when the page loads, it will never increment
// check if the SESSION exists, and if it doesn't, then we create it
if(!isset($_SESSION['t'])) {
$_SESSION['t'] = 0;
}
?>
<div id="test" class="test"></div>
<!-- it's recommended to load scripts at the end of the page -->
<script src="http://code.jquery.com/jquery.js"></script>
<script>
function update() {
// you had some formatting issues in here...
// shortcut: using +=1 will take the current value of $_SESSION['t'] and add 1
var ct = "<?php echo $_SESSION['t'] += 1 ?>";
<?php echo "Value: " . $_SESSION['t']; ?>;
$("#test").html(ct);
}
$(document).ready(function() {
setInterval('update()', 1000);
});
</script>
UPDATE:
This is an example that will do what I think you're looking for. It will display the value of $_SESSION['t'] when the page is loaded, and then increment the value of $_SESSION['t'] every time the update button is clicked. There is no error checking, this is just a very simple example to show you how this works.
<?php
session_start();
if(!isset($_SESSION['t'])) {
$_SESSION['t'] = 0;
}
?>
<div id="test" class="test"></div>
<button type="button" id="update">Update</button>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function() {
// create the ct varaible
var ct = <?php echo $_SESSION['t']; ?>;
// display the value in the #test div
$("#test").text(ct);
// when the update button is clicked, we call ajax.php
$("#update").click(function(){
$.post("ajax.php", function(response){
// display the returned value from ajax.php
$("#test").text(response);
});
});
});
</script>
ajax.php
<?php
session_start();
// increment the session by 1
$_SESSION['t'] += 1;
// return the result
echo $_SESSION['t'];

JQuery ignoring click() and change()

Advance note: I have already looked at and looked at and tried the solutions in the SO question: Jquery checkbox change and click event. Others on SO deal more with reading the values rather than the issue that the event is not firing.
I will admit that I am a relative newbie to JQuery.
I am trying to make two changes. One when a text field changes and one when a checkbox is toggled. Both are within a form. The idea is that if the text field changes a computation is done and the return value is written into the text after the checkbox. The checkbox toggles that text on and off.
Once finished the form can be submitted.
the code (as seen below) also uses php.
I've pulled the relevant code. I read several examples on line so there is are attempts using
<span id="foo"><input></span>
<input class='romanCheck' id='romanCheck' type='checkbox'>
Neither alert is being called. JSFiddle kinda barfed on the PHP. For the checkbox I've tried both .change() and .click()
The browsers I've tested on are all Mac (my dev environ)
Safari: 7.0.3 (9537.75.14)
Chrome: 33.0.1750.152
Firefox: 28.0
I've attached the relevant code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Not Working.php</title>
<link rel="stylesheet" href="jquery-ui-1.10.4.custom/css/ui-lightness/jquery-ui-1.10.4.custom.css">
<script src="jquery-ui-1.10.4.custom/js/jquery-1.10.2.js"></script>
<script src="jquery-ui-1.10.4.custom/js/jquery-ui-1.10.4.custom.js"></script>
</head>
<body>
<script>
function romanize (num) {
return "(" + "roman for " + ")";
}
$(document).ready(function(){
$(".romanCheck").live("change",function() {
alert("#romanCheck.click has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
$("span.iterationField input").live("change",function() {
alert("#iteration.change has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
});
</script>
<form action='EventValidateProcess.php' method='post'>
<?php
$doesShow = 1;
$isRoman = 1;
$iteration - 13;
print "<table>\n";
print "<tr>\n\t<td>Iteration</td>\n\t";
print "<td><span id='iterationField'><input type='text' name='iteration' value='" . $iteration . "'></span></td>\n\t";
print "<td><input type='checkbox' name='doesShow' value='1'";
if ($doesShow == 1) {
print " checked";
}
print "> visible | ";
print "\n<input class='romanCheck' id='romanCheck' type='checkbox' name='isRoman' value='1'";
if ($isRoman == 1) {
print " checked";
}
print "> uses Roman numerals\n";
print "<span id='romanDisplay'>(XX)</span></td>\n</tr>\n";
?>
</table>
<button type='submit' name='process' value='update'>Update</button><br/>
</form>
</body>
.live() deprecated: 1.7, removed: 1.9
Use .on() as you are using jquery-1.10.2
Syntax
$( elements ).on( events, selector, data, handler );
$(document).on("change", "span.iterationField input" ,function() { //code here });
$(document).on("change", ".romanCheck" ,function() { //code here });
span.iterationField is not exist, instead span#iterationField,
and just use:
$(document).ready(function(){
$("input.romanCheck").on("change",function() {
alert("#romanCheck.click has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
});
Note: make sure jquery library in imported
After a lot of finessing it seemed the answer that worked best was the following:
$(document).change("input.romanCheck", function() {
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $("#iterationField").val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
$(document).change("input.iterationField", function() {
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $("#iterationField").val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
Using:
print
"<input id='iterationField' type='text' name='iteration' value='";
print $iteration . "'/>";
print
"<input id='romanCheck' type='checkbox' name='isRoman' value='1'";
if ($isRoman == 1) {
print " checked";
}
print ">";
print "<span id='romanDisplay'>";
if ($isRoman == 1) {
print "(" . $romanIteration . ")";
}
print "</span>";
Im not sure what is your problem but try this.
function romanclick(){
//if event fire twice use namespace at 1. and 2. and put $(document).off('namespace') here
//your code romanclick
$('span.iterationField input').click(function(){
textchange();// call it again
});
}
function textchange(){
//if event fire twice use namespace at 1. and 2. and put $(document).off('namespace') here
//change text code
$('.romancheck').click(function(){
romanclick();// call it again
});
} ;
1.$(document).on("change", "span.iterationField input" ,function() { //call your function here });
2.$(document).on("change", ".romanCheck" ,function() { //call your function here });

Javascript - How to add a pause button in carousel?

I have found this script in Magento which is rotating images from a certain directory. This is working fine. But I need to add a "pause" button after the "1-6". I am not an expert on javascript so not sure how to do this. Can someone please help me with this?
The code:
<?php
$speed = 5000;//miliseconds
?>
<script type="text/javascript">
var timeoutID;
homeTileCount = 1;
$$('.home-tile-container img').each(function(e){
$(e).writeAttribute('id','home-tile-' + homeTileCount);
$(e).addClassName('home-tile');
homeTileCount++;
});
homeTileCount--;
var homeTileRemote = $$('.home-tile-remote')[0];
for (i=homeTileCount;i>=1;i--)
homeTileRemote.insert('<div id="home-tile-remote-'+i+'" class="overflow">'+i+'</div>');
function switchTile(n)
{
//console.log(n);
clearTimeout(timeoutID);
$$('.home-tile-container img').each(function(e){
e.removeClassName('home-tile-active');
});
$$('.home-tile-remote > div').each(function(e){
e.removeClassName('home-tile-remote-active');
});
$('home-tile-remote-'+n).addClassName('home-tile-remote-active');
$('home-tile-'+n).addClassName('home-tile-active');
next = n+1;
if (next > homeTileCount)
next = 1;
timeoutID = setTimeout('switchTile('+next+')', <?=$speed?>);
}
switchTile(1);
setTimeout('switchTile(2)', <?=$speed?>);
</script>
And this is how the carousel looks:
Maybe this:
<?php
$speed = 5000;//miliseconds
?>
<script type="text/javascript">
var paused=false;
var timeoutID;
homeTileCount = 1;
$$('.home-tile-container img').each(function(e){
$(e).writeAttribute('id','home-tile-' + homeTileCount);
$(e).addClassName('home-tile');
homeTileCount++;
});
homeTileCount--;
var homeTileRemote = $$('.home-tile-remote')[0];
for (i=homeTileCount;i>=1;i--)
homeTileRemote.insert('<div id="home-tile-remote-'+i+'" class="overflow">'+i+'</div>');
function switchTile(n)
{
if (!paused) {
//console.log(n);
clearTimeout(timeoutID);
$$('.home-tile-container img').each(function(e){
e.removeClassName('home-tile-active');
});
$$('.home-tile-remote > div').each(function(e){
e.removeClassName('home-tile-remote-active');
});
$('home-tile-remote-'+n).addClassName('home-tile-remote-active');
$('home-tile-'+n).addClassName('home-tile-active');
next = n+1;
if (next > homeTileCount)
next = 1;
timeoutID = setTimeout('switchTile('+next+')', <?=$speed?>);
}
}
switchTile(1);
setTimeout('switchTile(2)', <?=$speed?>);
</script>
<button type="button" onclick="paused=true;">Pause</button>

Javascript timer not looping along with mysql_fetch_array results

<? while($row = mysql_fetch_array($result))
{
$result2 = $row['end_time'];
echo"<td><div id=defaultCountdown></div></td>";
?>
<script type=text/javascript>
$(function ()
{
var t = ('<? echo $result2; ?>').split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
$('#defaultCountdown').countdown({until: d});
$('#year').text(austDay.getFullYear());
});
</script>
<? }
?>
So basically I wanted to launch the Javascript countdown timer for each row of results generated by mysql_fetch_array. However, in the code above, the timer only works for the first row of result. How do I make the timer work for every row of result?
EDIT
<td> 2012-12-17 13:12:22</td><td> <img src = Images/1324133424.jpg height=200 width=300 /> </td><td> active</td><td><div id=defaultCountdown0></div></td>
<script type=text/javascript>
$(function ()
{
var t = ('2012-12-17 13:12:22').split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
$('#defaultCountdown0').countdown({until: d});
$('#year').text(austDay.getFullYear());
});
</script>
<td> 2012-12-01 13:12:22</td><td> <img src = Images/1322754818.jpg height=200 width=300 /> </td><td> active</td> <td><div id=defaultCountdown1></div></td>
<script type=text/javascript>
$(function ()
{
var t = ('2012-12-01 13:12:22').split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
$('#defaultCountdown1').countdown({until: d});
$('#year').text(austDay.getFullYear());
});
</script>
In your PHP while loop, you are setting the same ID for all divs, which is probably why only the first row works. However, as I said in my comment, you need to add the actually JavaScript that is generated by your PHP code.
echo"<td><div id=defaultCountdown></div></td>";
EDIT:
Here's what the code should look like. Run it as it is and then try making small changes to get it to do what you want:
<?
while($row = mysql_fetch_array($result))
{
$i = 0;
$result2 = $row['end_time'];
echo "<td><div id=defaultCountdown$i></div></td>";
?>
<script type=text/javascript>
$(function ()
{
var t = ('<? echo $result2; ?>').split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
$('#defaultCountdown<?php echo $i; ?>').countdown({until: d});
$('#year').text(austDay.getFullYear());
});
</script>
<?
$i++;
}
?>

Categories