1

Iam using dropdown box which is implemented using JQuery-select2 version 3.5.

I want to set the 2'nd item selected from the list like $("#fieldId").prop("selectedIndex",1) using JQuery.

Is it possible?

Thanks in advance

Ponnarasu
  • 635
  • 1
  • 11
  • 24

3 Answers3

3
$('#fieldId').select2("val",$('#fieldId option:eq(1)').val());
/*By using eq(), the index number should be calculated from 0*/

or

$('#fieldId').select2("val",$('#fieldId option:nth-child(2)').val());
/*By using nth-child(), the index number should be calculated from 1*/

This may be useful

  • Your answer is correc but.already using this and mentioned this in comment. Anyway accepting your answer to help others – Ponnarasu Sep 07 '16 at 05:25
0

If you mean the select drop down menu then This should solve your problem

<select>
    <option>1st item</option>
    <option selected>2nd item</option>
    <option>3rd item</option>
</select>

Edit: You can achieve that like this

$('select option:nth-child(2)').attr('selected', true);
KANAYO AUGUSTIN UG
  • 2,078
  • 3
  • 17
  • 31
  • While loading the option list in ajax response, i have made the option selected as you said. That worked fine. Is there any other way like ' $("#fieldId").prop("selectedIndex",1); ' using JQuery? – Ponnarasu Aug 09 '16 at 06:35
  • Here I edited my answer @Pannarasu. Please don't forget to up vote and mark it as the answer – KANAYO AUGUSTIN UG Aug 09 '16 at 14:22
  • Your answer is working with normal dropdown using JQuery. But i have implemented dropdown using select2 jQuery, so it is not working. I got some idea from google and made some changes in your answer as $('#fieldId').select2("val",$('#fieldId option:eq(1)').val()) or $('#fieldId').select2("val",$('#fieldId option:nth-child(2)').val()) . This is working well. @KANAYOAUSTINKANE. So please make changes in your answer – Ponnarasu Aug 09 '16 at 17:30
0
$('#selectId').find('option').each(function(index,element){
    if(element.value.toLowerCase().trim() == 'VAL_TO_MATCH'){
         $("#selectId").prop('selectedIndex', index).change();
    }
});
Harit Kumar
  • 217
  • 2
  • 5
  • 2
    Welcome to SO. Code-only answers may address the issue but they are more useful if you add explanation as well. – Nick May 27 '19 at 11:31