Tintin81
Tintin81

Reputation: 10215

How to update select options with jQuery?

In my form I have two select boxes:

<select id="base_plan">
  <option value="free">Free</option>
  <option value="basic">Basic</option>
  <option value="premium">Premium</option></select>
</select>

<select id="plan_id">
  <option value="placeholder_weekly">Weekly</option>
  <option value="placeholder_monthly">Monthly</option>
  <option value="placeholder_yearly">Yearly</option>
</select>

I am trying to update the values of all the options in the second select box depending on the option chosen in the first select box.

I tried something like this...

$('#base_plan').on('change', function() {   
    var new_value = this.value;     
    $('#plan_id option').val().replace("placeholder", new_value); 
});

..but it's not working at all.

Can anybody help?

Upvotes: 1

Views: 40

Answers (1)

dfsq
dfsq

Reputation: 193311

You can provide a function for val method:

$('#base_plan').on('change', function() {   
    var new_value = this.value;     
    $('#plan_id option').val(function(_, oldVal) {
        return new_value + '_' + oldVal.split('_')[1];
    });
});

Note, that after changing values for the first time, they no longer have placeholder part, that's why instead of replace('placeholder', new_value) it's better to replace the part before _. For example by using split method and string concatenation.

Check the demo below.

$('#base_plan').on('change', function() {   
    var new_value = this.value;     
    $('#plan_id option').val(function(_, oldVal) {
        return new_value + '_' + oldVal.split('_')[1];
    });
    
    // Logging new values
    $('#log').html($('#plan_id option').map(function() {
        return this.value;
    }).get().join('\n'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="base_plan">
  <option value="free">Free</option>
  <option value="basic">Basic</option>
  <option value="premium">Premium</option></select>
</select>

<select id="plan_id">
  <option value="placeholder_weekly">Weekly</option>
  <option value="placeholder_monthly">Monthly</option>
  <option value="placeholder_yearly">Yearly</option>
</select>

<pre id="log"></pre>

Upvotes: 3

Related Questions