I have a number of HTML select boxes which are created by a do-while loop in PHP. Typically, the number of boxes varies from 1 to about 6. Then I have a line of checkboxes that are created the same way. The select boxes offer a choice of numbers, say 0 to 5. When a select box has been selected for a value of 1 or more, I want to hide the corresponding checkbox.
The real page is over 500 lines so it becomes difficult to see the wood for the trees. For test purposes I have created a minimalist file to play around with. The code I have at the moment is:
<?php
// Loop through the rooms
$i=1;
do {
$roomtype = $row_room['roomtype'];
$room_id = $row_room['room_id'];
$roomnumber = $row_room['number'];
$selectroom = "<div><br>
<br>
ID ".$room_id." <select id=\"s".$room_id."\" name=\"numrooms[".$room_id."]\">";
$selectroom .= "<option value=\"\" selected>Select</option>";
$k=1;
if ($roomnumber ==NULL||$roomnumber ==0||$roomnumber >5) {$roomnumber = 5;};
while ($k<=$roomnumber) {
$selectroom .= "<option value=\"".$k."\"> ".$k."</option>";
$k++;
}
$selectroom .= "</select></div>";
echo $selectroom;
?>
<script>
$('#s<?php echo $room_id ?>').change(function(){
if($(this).val()>0){
$('#<?php echo $room_id ?>').css('display', 'none');
}else{
$('#<?php echo $room_id ?>').css('display', 'inline-block');
}
});
</script>
<?php } while ($row_room = mysql_fetch_assoc($room));
?>
<br>
<br>
<?php // Alternative room choice
mysql_data_seek($room,0);
while ($row_room = mysql_fetch_assoc($room)) { ?>
<label id="<?php echo $row_room['room_id'] ?>" style="display:inline-block"><input name="altroom[]" type="checkbox" value="<?php echo $row_room['roomtype'] ?>">
<?php echo "Item with ID ".$row_room['room_id']." "; ?></label>
<?php }?>
As you can see, the jQuery script that does the hiding is placed inside the do-while loop and is therefore repeated multiple times (with variations in the values). This seems to me to be a very crude and inelegant solution. I would like to move the script outside the php and have it just once. How can I achieve this?
EDIT: Cracked it!
I added:
onchange=\"dropAlternative(".$room_id.")\"
to the HTML select and moved the Javascript to the end of the page body.
Then the script became:
function dropAlternative(roomID) {
if($('#s' + roomID).val()>0){
$('#' + roomID).css('display', 'none');
}else{
$('#' + roomID).css('display', 'inline-block');
}
}
This is probably totally unimpressive to the Javascript experts on here, but as a Javascript numpty, I'm feeling very pleased with myself.