简体   繁体   中英

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!

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

You can use dependent select jquery plugin for this purpose:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM