Change of option of a select by text and no attribute

2

With this <select>

<select id="idselect">
  <option value="1" data-msg="111">Personalizado</option>
</select>

To change the option to <select> in jquery I have for example these options

$('#idselect').val('1').attr('selected','selected')
$('#idselect > option[value="1"]').attr('selected','selected')
$('#idselect > option[data-msg="111"]').attr('selected','selected')

But it's with value or custom attributes

I would like to know how you can change the option by indicating the text 'Custom' and not by any attribute.

    
asked by Takyo 03.11.2016 в 18:01
source

2 answers

2

I'll give you an example, the crux of the matter is in the use of the jQuery selector contains

$("a[data-select]").click(function(){
  var texto_de_option = this.getAttribute('data-select').trim();
  $("#idselect").find('option:contains("'+texto_de_option+'")').prop('selected', true);
});
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="idselect">
      <option value="1" data-msg="111">Personalizado1</option>
      <option value="2" data-msg="222">Personalizado2</option>
      <option value="3" data-msg="333">Personalizado3</option>
      <option value="4" data-msg="444">Personalizado4</option>
    </select>
    <br><br>
    <a href = "javascript:;" data-select='Personalizado1'>Seleccionar Personalizado1</a>
    <br><br>
    <a href = "javascript:;" data-select='Personalizado2'>Seleccionar Personalizado2</a>
    <br><br>
    <a href = "javascript:;" data-select='Personalizado3'>Seleccionar Personalizado3</a>
    <br><br>
    <a href = "javascript:;" data-select='Personalizado4'>Seleccionar Personalizado4</a>
    
answered by 03.11.2016 / 18:34
source
3

You can use the selector: contains () to check the text within <option> .

$(function(){
  
  $('button').on('click', function(){
    
     $('#idselect option:contains("Personalizado")').attr('selected','selected');
    
  });
});
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<select id="idselect">
  <option>select</option>
  <option value="1" data-msg="111">Personalizado</option>
  <option value="2" data-msg="112">otra cosa</option>
</select>
  
<button>Elegir Personalizado</button>
  
  
    
answered by 03.11.2016 в 18:17