Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

160
Visualizações
I can't select an option using jquery

This is my HTML:

<div class="col-md-6">
  <div class="form-group">
    <label>Departement</label>
    <select class="form-control departement"
            name="worker_departement_edit"
            id="worker_departement_edit" 
            required >
      <option class="default" disabled selected value="">
         Please select a departement!
      </option>
    </select>
    <div class="invalid-feedback">
      Please select an option!
    </div>
  </div>
</div>

And this is a event when I click the edit button to append option inside the select:

$(".departement").append('<option value="' 
                        + element['id_departement'] 
                        + '">' + element['depart_name'] 
                        + '<option>')

And this is my code when I want to select an option:

$("#worker_departement_edit").children(".default-depart").remove()
$("#worker_departement_edit").val(datas[0]["departement"]).change();

I was console.log this $("#worker_departement_edit").children(".default-depart") and it's was fine also I try to console.log the variable datas and its was fine too

What i've try:

$(".default-depart").remove()
$(".worker_departement_edit")
 .children('option[value=' 
          + datas[0]["departement"] 
          + ']')
 .attr("selected", true)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You should use prop().

Both attr() and prop() are used to get or set the value of the specified property of an element attribute, but attr() returns the default value (Original state) of a property whereas prop() returns the current value (Current state).

$("#worker_departement_edit").val(datas[0]["departement"])
$("#worker_departement_edit").find('option[value='+datas[0]["departement"]+']').prop("selected", true)
about 4 years ago · Juan Pablo Isaza Relatório

0

Your code mostly works fine. I've included a a working, simplified version of your code below, click Run to see it in action.

A few things I noticed:

  • Your .append() code uses <option> ... <option> - that last tag should be a closing tag, </option>;

  • There is no element with class default-depart, so you can't remove it, and that code is not doing anything (unless that element exists but you have not included it here);

  • It would make it much easier for ppl to help if you can create a MINIMAL, complete, and verifiable example - that means including a small part of your datas array, and removing CSS, HTML, etc not related to this specific problem;

  • This question is really a duplicate, and should be closed I think, eg: Set select option 'selected', by value

var datas = [
    {id: 1, department: 'Work'},
    {id: 2, department: 'Fun'},
    {id: 3, department: 'Lunch'},
];

var $select = $(".departement"),
    $info = $('#info');

$('#add').on('click', function(e) {
    e.preventDefault();
    $select.append('<option value="' 
        + datas[2]['id']
        + '">' + datas[2]['department']
        + '</option>');
    $info.append('Option added!<br>');
});

$('#select').on('click', function(e) {
    e.preventDefault();
    $select.val(datas[2]['id']).change();
    $info.append('Option selected!<br>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label>Departement</label>
<select class="departement" name="worker_departement_edit" id="worker_departement_edit">
    <option class="default" disabled selected value="">Please select a departement!</option>
</select>

<p>
    <button id="add">Add An Option</button>
    <button id="select">Select An Option</button>
</p>

<p id="info"></p>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda