3

This is how the flow like:

I first derive the value of checkbox and pass the value to a function to trigger ajax. That ajax function return a list of data in multiple group in select box. Each time a checkbox checked, the value will be appended into the selectbox. But I want to remove the value from selectbox when checkbox unchecked.

Now, when I click on the checkbox the value is passed to the function no matter I check or uncheck. How to control here?

first script

<script>

    $("input[type=checkbox]").change(function() {  
        var selectedval = ($(this).val());
        var selectedtext =($(this).next().text());

       sendtobox(selectedval);

    });
</script>

second script (function)

<script>
            var xmlhttp = false;
            try
            {
                xmlhttp = new ActiveXObject(Msxml2.XMLHTTP);
                //alert("javascript version greater than 5!");
            }
            catch(e)
            {
                try
                {
                    xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
                   // alert("you're using IE!");
                }
                catch(E)
                {
                    xmlhttp = new XMLHttpRequest();
                    //alert("non IE!");
                }
            }

            function sendtobox(param)
            {
                 xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            if (this.responseText !== null) {
            var ajaxElm = document.getElementById('show');
            ajaxElm.innerHTML = this.responseText + ajaxElm.innerHTML; // append in front
             }
                //document.getElementById("show").innerHTML = xmlhttp.responseText;
            }
            }

                 xmlhttp.open("GET","getuser.php?q="+param,true);
                 xmlhttp.send();

            }
        </script>

HTML

 <input type="checkbox" name="level" id="level" class="level" value="1"><label>Primary</label><br/>
                <input type="checkbox" name="level" id="level" class="level" value="2"><label>Upper Secondary</label><br/>
                <input type="checkbox" name="level" id="level" class="level" value="3"><label>University</label><br/>
                <input type="checkbox" name="level" id="level" class="level" value="4"><label>Lower Secondary</label><br/>
                <input type="checkbox" name="level" id="level" class="level" value="5"><label>Pre University</label><br/>
                <input type="checkbox" name="level" id="level" class="level" value="6"><label>Skills/Languages</label><br/>

getuser.php

<?php
 $q= intval($_GET['q']);

$con = mysqli_connect('localhost','root','','wordblend_db');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"test_db");
//$sql="SELECT * FROM tbl_subjects WHERE level_id = '".$q."'";
$sql="SELECT * FROM tbl_levels,tbl_subjects WHERE tbl_levels.level_id=tbl_subjects.level_id AND tbl_levels.level_id='$q'";
$result = mysqli_query($con,$sql);

?>

<?php
while($row = mysqli_fetch_array($result)) {

    $levels=$row['level_name'];
    $subjects= $row['subject_name'];
    $subjects_id= $row['subject_id'];

    ?>

       <optgroup label="<?php echo $levels;?>">
            <option value="<?php echo $subjects_id;?>"><?php echo $subjects;?></option>
        </optgroup>

    <?php

}

?>
sweety
  • 195
  • 1
  • 11
  • Btw, if your DB contains any real world data, read this http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – ekuusela Apr 19 '15 at 12:59

2 Answers2

1

In onchange event, check for the checked status of the checkbox and then perform action accordingly.

 $("input[type=checkbox]").change(function() {  
     if($(this).is(":checked")) {
        var selectedval = $(this).val();
        var selectedtext = $(this).next().text();
        sendtobox(selectedval);
     }
      else {
        // remove the items 
     }
    });

Regarding removal of items, you must track which values are added for that particular checkbox. Only then you can remove those particular items.

EDIT based on comments

In your PHP code, add an identifier for the items added based on the checkbox. I'm adding the $q itself which is the checkbox value as class name.

<optgroup label="<?php echo $levels;?>" class="<?php echo $q;?>">
       <option value="<?php echo $subjects_id;?>"><?php echo $subjects;?></option>
</optgroup>

Now in your jquery code:

 $("input[type=checkbox]").change(function() {  
     var selectedval = $(this).val();
     if($(this).is(":checked")) {
        var selectedtext = $(this).next().text();
        sendtobox(selectedval);
     }
      else {
        $("optgroup."+selectedVal).remove();
     }
    });

Now this will remove the optgroups added by the ajax call.

mohamedrias
  • 18,326
  • 2
  • 38
  • 47
  • actually I tried this way, but I can't get the removing part right. document.getElementById('level').remove(); removes the checkbox straight away.Is there anyway to remove the item from the appended list please? – sweety Apr 19 '15 at 12:32
  • sure, please share code of the select menu items and what's the ajax response look like – mohamedrias Apr 19 '15 at 12:36
  • @sweety I don't know if I understand your question correctly but one thing that is wrong with your code is that your html elements don't have unique identifiers. – ekuusela Apr 19 '15 at 12:37
  • @mohamedrias, I updated the php file that respond to ajax call.Please have a look. – sweety Apr 19 '15 at 12:49
  • Great, you may need to append the levelId to your `optgroup` or to `options` which you're appending as classname. only then you will be remove those when the user uncheck them – mohamedrias Apr 19 '15 at 12:55
  • @mohamedrias can u give in code example please, I just can't find the way out! – sweety Apr 19 '15 at 15:22
  • @sweety Updated my answer. You can check that :) – mohamedrias Apr 19 '15 at 15:40
0

Check the checked property of the checkbox.

$("input[type=checkbox]").change(function() {  
    var selectedval = ($(this).val());
    var selectedtext =($(this).next().text());
    if (this.checked) {
        // do something else
    } else {
        sendtobox(selectedval);
    }


});

Edit:

About removing, I assume you wish to undo on uncheck what you do here:

ajaxElm.innerHTML = this.responseText + ajaxElm.innerHTML;

Instead of adding the response text directly, add it as a new dom element inside the show element with some unique identifier you can later use to remove it. Something like this (I use jquery since you seem to use that too in your first script, this is all doable without it of course):

var ajaxElm = $('#show');
ajaxElm.append($('<span id="uniqueidgoeshere">').append(this.responseText))

And then when you remove it refer to that id. The id should be deducible from the id (or other attributes) of the changed checkbox.

ekuusela
  • 5,034
  • 1
  • 25
  • 43
  • ,can you tell me how to remove item please? – sweety Apr 19 '15 at 12:37
  • the call to sentobox() function is now made. no matter the checkbox or unchecked. Then in the function ajax call is made to fetch and display data from db which is from the file getuser.php. BUt how do I remove the item from the appended list, if the same value is passed to the function maybe? – sweety Apr 19 '15 at 12:48
  • thanks for ur help but I just not sure how to append unique id to my optgroup(how to get the id). – sweety Apr 19 '15 at 13:13
  • You could use the value as a part of the ID. Note that IDs must begin with a letter. Also, you don't necessarily have to have an ID, just something unique that ties together the clicked checkbox and the related option (which I think the value already does) that you can use to find the proper elements. – ekuusela Apr 19 '15 at 13:20
  • ,okay I'll try my best – sweety Apr 19 '15 at 13:23