I have an array of checkbox that is populated with data from mysql database through a query. I can submit the value of the checked checkbox into a table from a database. But I want it to be saved according to the sequence the checkbox was checked by the user. I was told that I can achieve this through javascript but I'm not that familiar with javascript. Can you please guide me on how to do this? Any help will be appreciated. Thanks a lot!

submit your code then we may able to help you.

Here's my code:

<?php
require("aacfs.php");
echo"<div align= center >
  <table width=300 border= 1 align= right><tr><th align=center bgcolor=silver><font face=consolas>Choose Itinerary</font></th></tr>
    <tr>
      <td></br>
      <form method=post>"; 


$result=mysql_query(" select * from itinerary group by location");
    $y=mysql_affected_rows();
    for($i=0;$i<$y;$i++)
    {$row=mysql_fetch_array($result);
        $pr=$row['icode'];
        $n=$row['location'];
        $l=$row['btime'];
echo"<table border=1 align=center width=250>
          <tr><td width=15><input name=prod[] type=checkbox value='$pr'></td><td>$n</td></tr>
          </table>";
        $t=$_POST[prod];

        }
echo"</td></tr></table>";

echo"      

    <table width= 664 border= 1  align= left >
    <tr><td height= 282 ><p align= center  class= style77>
<p align= right ><h4>$d</h4></p>
<p align= center ><font face=consolas><b>Itinerary List</b></font></p>
<p align=center><font face=consolas>To change your itinerary list, choose again.</font></p>

<br>
  <center><input name=add  type= submit  value='Add to Itinerary List'></center>
<br>  
<table width=654  border= 1>
  <tr bgcolor = silver align=center>
    <td>Itinerary</td>
    <td>Block Time</td>

 </tr></form>";


 if(isset($_POST['add']))
{           
if(isset($_POST[prod]))
 {  foreach($t as $k)
    {$result=mysql_query("select * from itinerary where icode='$k'");
    $y=mysql_affected_rows();

for($x=0;$x<$y;$x++)
{$row=mysql_fetch_array($result);
        $r=array($row['icode']);
        $n=$row['location'];
        $p=$row['btime'];   



    echo"<form method=post><tr>
<td>$n</td>
<td>$p</td>
 </tr>";

    $a=$_POST[pro];
    $stat1='Not Submitted';

foreach($r as $a=>$l)
{

$kdot=mysql_query("select max(reservno) as 'maxr' from reservation") or die(mysql_error());
$row2=mysql_fetch_array($kdot);
$fi=$row2['maxr'];
mysql_query("insert into location_list(reservno, icode, location, status) values('$fi', '$l', '$n', '$stat1')") or die(mysql_error());
}
}}}

}

I am adding hidden field for each icode next to check box

<?php

for (..)
{
<input name=prod[] type=checkbox value='$pr' onclick='javascript:setorder(this);'>
<input name='cd-$pr' id='cd-$pr' type=hidden value=''>
}
?>

now I am adding java script at the end of page

<script lang='javascript'>
var chkorder=1;
function setorder(chkbx)
{
   if(chkbx.checked)
   {
      document.getElementById('cd-'+chkbx.value).value=chkorder++;
   }
   else
   {
      document.getElementById('cd-'+chkbx.value).value='';
   }
}
</script>

Now in submit page you can get order of icode by following code

<?php
for ($i=0;$i<count($_POST[prod]);$i++)
{
    echo "icode={$_POST['prod'][$i]}  , chk order=$_POST['cd-'.{$_POST['prod'][$i]]}    ";
}
?>

SYNTAX IS NOT TESTED

Got it working with this javascript code binded with my previous code:

<script type="text/javascript"> 
<!--

$(document).ready(function(){

    var array = [];
     //var array2 = [];


    $("input[type=button]").click(function(){
    for (var i = 0; i < array.length; i++){  
    if (array[i] == $(this).attr('value')){  
    array.splice(i, 1);  
    }  
    }  
    alert(array.length);
    });




    $('input[type="checkbox"]').click(function(){

    if ($(this).attr('checked')){
    // Add the new element if checked:  
    array.push($(this).attr('value'));
    //alert(array2.push($(this).attr('name')));
    }

    else{ 
    // Remove the element if unchecked:  
    for (var i = 0; i < array.length; i++){  
    if (array[i] == $(this).attr('value')){  
    array.splice(i, 1);
    }
    }
    /* if (array2[i] == $(this).attr('name')){  
    array2.splice(i, 1);
    }
    }*/
    }






        $("#result").show(function(){
        $(this).val("");
        for (var i = 0; i < array.length; i++){
    $(this).val($(this).val() + " " + array[i]+ "\n");
        }
        });

    });

}); 
//--> 
</script>

Thank you for your replies.

xjshiya,

You can considerably shorten the code and avoid having to maintain a dedicated sequence-tracking array by further exploiting jQuery and reading the DOM on the fly every time the button is clicked.

$(function(){
    var seq = 0,
        $ch = $('input[type="checkbox"]').on('click', function() {
            $(this).data('seq', seq++);
        });

    $("input[type=button]").click(function() {
        var str = Array.prototype.sort.call($ch.filter(":checked"), function(a, b) {
            return $(a).data('seq') - $(b).data('seq');
        }).map(function(i, el) {
            return el.value;
        }).get().join("\n");
        $("#result").text(str).show();
    });
});

See DEMO

This code is not particularly straightforward. Much is achieved in a method chain, which in simplified form reads :

Array.prototype.sort.call(jQueryObj, fn{}).map(fn{}).get().join(String);

Array.prototype.sort.call(...) is used because jQuery doesn't have its own sort method so jQueryObj.sort(fn{}) simply wouldn't work. However 'jQueryObj' is array-like and can be sorted by invoking Array's sort method on it.

.map() and .get() are jQuery methods. join() is raw javascript.

The sequence counter seq is never reset. It is allowed to grow and grow, which is safe in the life of a web page given the extent of javascript's Number range.

Here's a slightly better formulation in which the jQuery object $ch is manipulated to reflect selection order of the checkboxes.

$(document).ready(function() {
    var seq = 0,
        $wrapper = $("#wrapper"),
        $ch = $('input[type="checkbox"]', $wrapper);
    $wrapper.on('click', 'input[type="checkbox"]', function() {
        if (this.checked) {
            $ch = $ch.not(this);//remove from jQuery 'array'
            Array.prototype.push.call($ch, this);//add to end of jQuery 'array'
        }
    });

    $("input[type=button]", $wrapper).on('click', function() {
        var str = $ch.filter(":checked").map(function(i, el) {
            return el.value;
        }).get().join("\n");
        $("#result").text(str).show();
    });
});

See DEMO

This version is actually similar to xjshiya's original version except the jQuery object $ch is kept up to date instead of a javascript array. jQuery's .not() and Array.prototype.push allow the jQuery object to be manipulated in such a way that it is unnecessary to reset it, and to keep the code concise.

I just checking reply work or not , sorry for this post

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.