I have a form with two inputs where the user has to select a number from two different sets. The first one is from 1 to 100. The second one is from 1 to 500, but I need to show only the remaining values above the number selected in the first input. Let's say I have a script like this:
<?php
echo "<form action='process.php' method='post'>";
echo "<select id='first_set' name='first_set'>";
echo "<option value='' disabled selected hidden>select how many</option>";
for ($i = 1; $i <= 100; $i ++) {
echo "<option value='" . $i . "'>" . $i . "</option>";
}
echo "</select>";
echo "<select id='second_set' name='second_set'>";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#first_set').on('change',function(){
var numFirstSet = $(this).val();
if(numFirstSet){
var topSecondSet = 500;
var numRemaining = topSecondSet - numFirstSet;
for (var a = numRemaining; a < topSecondSet; a ++) {
var numToDisplay = a;
$('#second_set').html('<option value="numToDisplay">numToDisplay</option>');
}
}else{
$('#second_set').html('<option value="">Select first a value from the set before!</option>');
}
});
});
</script>
<?php
// the submit button
echo "</form>";
?>
But it doesn't work. The second_set select sadly displays the word "numToDisplay", not the calculated value (var numToDisplay) nor the text "Select first a value from the set before!".
Edit: after some suggestions, I've tried with
$('#second_set').html('<option value="' + numToDisplay + '">' + numToDisplay + '</option>');
but got a strange result: after a select done in first_set, the numToDisplay value is shown but it's always 499. That is topSecondSet - 1 ! And no set of values.
I've tried to figure out a solution and wrote this code:
<script type="text/javascript">
$(document).ready(function(){
$('#first_set').on('change',function(){
var sel_box = document.getElementById("second_set");
var numFirstSet = $(this).val();
sel_box.selectedIndex = 0;
if(numFirstSet){
var topSecondSet = 100;
var startNum = numFirstSet + 1;
for (var a = startNum; a <= topSecondSet; a ++) {
var numToDisplay = a;
var option = document.createElement("option");
option.text = numToDisplay;
sel_box.add(option);
}
}else{
var selectfirstText = "Select first a value from the set before!";
sel_box.html = '<option value="">' + selectfirstText + '</option>';
}
});
});
</script>
Now second_set is populated after the change in first_set , but got two problems:
1) the items in second_set start from numFirstSet*10 instead of numFirstSet+1;
2) each time a change is made in first_set selection, a new set of options is added instead of substitute the previous set, despite the row
sel_box.selectedIndex = 0;
that has the goal of resetting the options before adding the new ones.
3) the code
var selectfirstText = "Select first a value from the set before!";
sel_box.html = '<option value="">' + selectfirstText + '</option>';
gives no output, it simply does not work.
Any idea to solve the three problems as above?