There are selected c options . There may be many options, depending on the purpose.
How do I get a certain option (say, the 10th in a row)?
I can only receive the first and the last, but how to choose by the index?
|
3 answers
You can get an element by its serial number through $(selector).eq(index) , or $('selector:eq(index)') , where index is the number of the element, starting from 0 . The first method is preferable, since easier to read and does not need manipulation with concatenation of strings and numbers (selector and index)
$('input').on('input', function(){ var val = $(this).val()*1; var option = $('select').find('option').eq(val); if(option.val() != undefined){ $('#out').html(option.val() + '<br/><b>Код команды:</b> $("select").find("option").eq('+val + ')'); $('#out_html').html(option.html()); $('select').val(option.val()); } }); //$('select') <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <b>Option number:</b> <input/><br/> <select style='margin-top:10px;'> <option value='opt_1'>FIRST</option> <option value='opt_2'>SECOND</option> <option value='opt_3'>THIRD</option> <option value='opt_4'>FOURTH</option> <option value='opt_5'>FIFTH</option> </select><br/> <b>Option value:</b> <span id='out'></span><br/> <b>Option html:</b> <span id='out_html'></span> - Thank you very much!)) W - elik
|
In javascript
document.querySelectorAll('.myselect option')[10] |
If the list of options looks like this:
<select name="" id="select"> <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> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> That problem to solve the problem like this:
pure js:
document.getElementById('select').options[9].value // получение значения 10-го элемента document.getElementById('select').options[9].text // получение текста 10-го элемента jQuery:
$('#select option:nth-child(10)').val() // получение значения 10-го элемента $('#select option:eq(9)').val() // получение значения 10-го элемента $('#select option').eq(9).val() // получение значения 10-го элемента // текст получаем аналогично через метод .text() - Your code does not work why - elik
- js does not plow, but jquery is ok! thanks kind - elik
- The @elik code was presented for review, because all options were collected in one - lexxl
|
$('.myselect').find('option').eq(10)? - SLy_huh