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
}
?>