1

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)
Leo
  • 1,990
  • 1
  • 13
  • 20
nayakaraga
  • 35
  • 4
  • What is `element` or `datas`? – Spectric Aug 26 '21 at 03:32
  • `element` is my variable on a function, the function is called when i click the edit button, i call the function to fill the select, the function is `get_departement()`. `datas` is my variable , after i call the `get_departement()`, i use ajax to get the a specific data for current data i clicked, if ajax success, i parse the return and place it to variable `datas`. – nayakaraga Aug 26 '21 at 03:40

2 Answers2

1

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)
S N Sharma
  • 1,436
  • 2
  • 7
  • 20
  • Still not working... this is the html element when i inspect after i click the edit button and trigger that code `` – nayakaraga Aug 26 '21 at 03:55
  • Remove `selected value=""` from default option. – S N Sharma Aug 26 '21 at 03:57
  • class `default-depart` is not in your html. How do you suppose to remove element using it? – S N Sharma Aug 26 '21 at 03:58
  • i cant remove the `selected value=""` because its needed for other element (because it was a global function). so i used jquery `$("#worker_departement_edit").children(".default-depart").removeAttr("selected").removeAttr("value")` and it worked, but it still cant select the option what i asked before – nayakaraga Aug 26 '21 at 04:01
  • I have updated my answer. Check now and one more thing `worker_departement_edit` is id but you are using it as class `$(".worker_departement_edit") .children('option[value=' + datas[0]["departement"] + ']') .attr("selected", true)` – S N Sharma Aug 26 '21 at 04:08
  • oh no, when i inspect the select the `selected value=""` is still there, but if i console.log the element it gone `` – nayakaraga Aug 26 '21 at 04:35
1

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>
Don't Panic
  • 13,965
  • 5
  • 32
  • 51