Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
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 :

    $(#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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>');
        }
    });
about 4 years ago · Juan Pablo Isaza Report

0

Different approach where you store a set of the options and filter the set to replace existing with

const $storedOpts = $('#second option').clone()

$('#first').change(function(){
    const $opts = $storedOpts .clone().filter((i,el) => el.value <= this.value)
    $('#second').html($opts);      
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!