Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Manipulate Select options with ajax

lets admit we have two selects

<select id=first>
<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>

<select id=second>
<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>

I want that the second select should not offer values that are bigger then the selected value in the first select, so if for example in the first select I selected 3 then the second select should offer

<select id=second>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

So I went like this :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    $(#first).on('change', function() {
        var min = $(#first).val();
        for (let i = 1; i <= min; i++) {
           $(#second).append('<option value=' + i + '>' + i + '</option>'); 
        } 
    });

But this appends options. I want to replace the options.

>Solution :

You can remove all <option> tags first by using .empty() and then append new <option> tags by loop:

    $('#first').on('change', function() {
        $('#second').empty();
        var min = $('#first').val();
        for (let i = 1; i <= min; i++) {
            $('#second').append('<option value=' + i + '>' + i + '</option>');
        }
    });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading