0

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?

gab
  • 77
  • 1
  • 1
  • 9
  • Does this answer your question? [How can I do string interpolation in JavaScript?](https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript) – Emiel Zuurbier May 11 '20 at 10:45
  • The `html()` method of jQuery overwrites the `innerHTML` value. So it doesn't add any element but only overwrites it. – Emiel Zuurbier May 11 '20 at 10:48
  • I've tried with `${numToDisplay}` inside the tags, but it simply displays the literal word "${numToDisplay}". So what code do you suggest? – gab May 11 '20 at 10:55
  • Try to use ${}, but with backticks (' ` ') around the string instead of single quotes (' ' '). Like this (stackoverflow formats it in grey though): $('#second_set').html(``); – Viktor W May 11 '20 at 11:02
  • Use backticks `\` \`` instead of quotes (`' '` or `" "`) to use the `${numToDisplay}` template literal injection. – Emiel Zuurbier May 11 '20 at 11:02
  • Change `a < topSecondSet` to `a <= topSecondSet` in your `for` loop to include the last number. – Emiel Zuurbier May 11 '20 at 11:35
  • Tried your last suggestione, but it gives the full `topSecondSet` value: 500. No subtractions neither any set series of numbers. Any idea on how to solve? – gab May 11 '20 at 12:34

1 Answers1

0

Here is a solution that appends a child not using Jquery. Look at Emiel Zuurbiers comments as well. I would also be careful using if(numFirstSet) becuase if the value is 0 it will evaluate as false. I think your intended result should have a check after document.ready and not in the onchange function. That way your "Select first value" option is there at runtime.

let firstSet = document.getElementById("first_set");

$(document).ready(function() {
  if (firstSet.value === "null") {
    $("#second_set").html(
      '<option value="">Select first a value from the set before!</option>'
    );
  }
  $("#first_set").on("change", function() {
    var numFirstSet = parseInt($(this).val());
    // console.log(numFirstSet);

    $("#second_set").html("");
    var topSecondSet = 50;
    var numRemaining = topSecondSet - numFirstSet;
    for (var a = numRemaining; a < topSecondSet; a++) {
      let opt = document.createElement("option");
      opt.innerHTML = a;
      opt.value = a;
      document.getElementById("second_set").append(opt);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="first_set">
    <option selected disabled value="null">Nothing</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
      </select>
      <br /><br />
      <select id="second_set"> </select>
  • it gives an error: `"message": "Uncaught TypeError: document.getElementById(...).append is not a function"` – gab May 11 '20 at 14:03
  • Changing `append` with `add` solved the error. But still `$("#second_set").html( '' );` does not give any output. Ideas? – gab May 11 '20 at 14:12
  • The reason the second option never rendered was because the `if()` was inside of your onchange event of the first select. The if statement needed to be ran when document was ready. – catmanfondue May 11 '20 at 14:25