Tintin81
Tintin81

Reputation: 10207

How to update a select box based on the values of another?

In my Rails app I have a form with two select boxes (one of them being a multiple select box):

<label>Project owners</label>
<select multiple="multiple">
  <option value="1">Huey</option>
  <option value="2">Dewey</option>
  <option value="3">Louie</option>
</select>

<label>Invoice recipients</label>
<select>
  <option value="1">Huey</option>
  <option value="2">Dewey</option>
  <option value="3">Louie</option>
</select>

How can I limit the invoice recipients to the project owners that have been selected?

For example, if Dewey and Louie get selected as project owners, the invoice recipients select box should only contain Dewey and Louie as well.

I know this is possible through jQuery but my jQuery skills are very limited.

Please help me. Thanks a lot!

Upvotes: 0

Views: 690

Answers (2)

Abhilash M A
Abhilash M A

Reputation: 564

You can use dependent select jquery plugin for this purpose:

http://simpleweb.github.io/jquery-dependent-selects/

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Try

<label>Project owners</label>
<select id="owners" multiple="multiple">
  <option value="1">Huey</option>
  <option value="2">Dewey</option>
  <option value="3">Louie</option>
</select>

<label>Invoice recipients</label>
<select id="recipients">
  <option value="1">Huey</option>
  <option value="2">Dewey</option>
  <option value="3">Louie</option>
</select>

then

$('#owners').change(function(){
    $('#recipients').empty().append($(this).find('option:selected').clone())
})

Demo: Fiddle

Upvotes: 5

Related Questions