javascript - Scroll down to selected option on button click using jquery -
i have list of countries this:
the list extensive. need able on button click move (focus) specified country.
there many threads in stackoverflow none of them worked. example tried this:
var code = 40; $('#id_resource-regions').val(code).scrolltop(160);
there no response , no error/warnings in developers tool. note list created using django forms , templates.
- select
option
element looking for. - get offset top position using .offset(), of selected option element.
- get offset top of select element.
- use .scrolltop() scroll desired option.
here example
var btn = $('button') var select = $('select') btn.on('click', function() { var option = select.find("option:contains('item-30')"); var optiontop = option.offset().top var selecttop = select.offset().top; select.scrolltop(select.scrolltop() + (optiontop - selecttop)); option.prop('selected', true) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="" id="select" multiple="multiple"> <option value="">item-1</option> <option value="">item-2</option> <option value="">item-3</option> <option value="">item-4</option> <option value="">item-5</option> <option value="">item-6</option> <option value="">item-7</option> <option value="">item-8</option> <option value="">item-9</option> <option value="">item-10</option> <option value="">item-11</option> <option value="">item-12</option> <option value="">item-13</option> <option value="">item-14</option> <option value="">item-15</option> <option value="">item-16</option> <option value="">item-17</option> <option value="">item-18</option> <option value="">item-19</option> <option value="">item-20</option> <option value="">item-21</option> <option value="">item-22</option> <option value="">item-23</option> <option value="">item-24</option> <option value="">item-25</option> <option value="">item-26</option> <option value="">item-27</option> <option value="">item-28</option> <option value="">item-29</option> <option value="">item-30</option> <option value="">item-31</option> <option value="">item-32</option> <option value="">item-33</option> <option value="">item-34</option> <option value="">item-35</option> <option value="">item-36</option> <option value="">item-37</option> <option value="">item-38</option> <option value="">item-39</option> <option value="">item-40</option> </select> <button>move item 30</button>
Comments
Post a Comment