Search code examples
javascriptvariablescheckboxhref

Pass checkbox value to Edit (using href)


I'm trying to get the value of the selected checkbox to be transfered to the next page using href. I'm not in a position to use submit buttons.I want this to be done using JavaScript.

My checkbox is populated with value from a table row-docid. Here is my code for Checkbox in view.php:

... mysql_connect("$host", "$dbuser", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $doctbl_name";
$result=mysql_query($sql);
if(!$result ){ die('Could not get data: ' . mysql_error()); }
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {  ?>
<tr><td><input type="checkbox"  name="chk_docid[]" id="<?php echo $row['docid'];?>" 
         value="<?php echo $row['docid'];?>"></td> ...

I have an EDIT Link as a menu in the top in view.php.

<a href="editdoc.php>Document</a>

My question : How do I pass the value of the checked checkbox when I click the edit link.

Note :I searched for a similar question, but could not find one. If I missed any similar question please provide me with the link.

Thanks in advance. Lakshmi

Note: changed the id of the checkbox from chk_docid to the dynamic row value ($row['docid']) as suggested by Jaak Kütt.


Solution

  • make sure your inputs have different id-s..

    while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {  ?>
    ...<input type="checkbox"  name="chk_docid[]" class="chk_input" 
    id="chk_docid<?php echo $row['docid'];?>" value="<?php echo $row['docid'];?>">...
    

    using jQuery:

    <a href="editdoc.php" id="editdoc">Document</a>
    
    $("#editdoc").click(function(){
        var selection=$("input.chk_input:checked");
        if(selection.length){
            var href=$(this).attr('href')+'?'+selection.serialize();
            $(this).attr('href',href);
        }
        return true;
    });
    

    non-jQuery:

    <a onclick="submitWithChecked(this,'chk_input')" href="editdoc.php">Document</a>
    
    function submitWithChecked(e,className){
        // fetch all input elements, styled for older browsers
        var elems=document.getElementsByTagName('input');                    
        for (var i = 0; i < elems.length; ++i) {
            // for each input look at only the ones with the class you are intrested in
            if((elems[i].getAttribute('class') === className || elems[i].getAttribute('className') === className) && elems[i].checked){
                // check if you need to add ? or & infront of a query part
                e.href+=(!i && e.href.indexOf('?')<0)?'?':'&';
                // append elements name and value to the query  
                e.href+=elems[i].name+'='+encodeURIComponent(elems[i].value);
            }
        }    
        return true;
    }
    

    in editdoc.php fetch the values with php using $_GET['name_of_input_element']