1

I have this dropdown and I'm trying to get the API value and select the value that corresponds to it but it always selects the first option.

How can I get the correct value/text of the option to the dropdown from API?

The dropdown from the view:

<select class="form-control select2" data-toggle="select2" id="Status" name="Status"></select>

API:

"Success": true,
"Message": "",
"Statuses": [
    {
        "Id": 1,
        "Name": "Nuevo"
    },
    {
        "Id": 2,
        "Name": "Leído"
    },
    {
        "Id": 3,
        "Name": "Atendido"
    }
]

The dropdown is filled with the values from the API and I have a grid where I have to update the status of the data, and when selecting, it must bring the value it has from the api

Function to get all the status:

function LoadMailboxStatus() {
    var dropDown = $("#Status");
    dropDown.empty();

    $.ajax({
        type: "GET",
        url: "/Mailbox/GetStatuses/",
        error: (result) => $.Notification.error(result),
        dataType: 'json',
        success: function (result) {
            if (result.Success) {
                var status = result.Statuses;
                $.each(status, function (key, item) {
                    dropDown.append($('<option></option>').attr('value', item.Id).text(item.Name));
                    $('option', this).each(function () {
                        if ($(this).html() == item.Name) {
                            $(this).attr('selected', 'selected')
                        };
                    });
                })
            }
            else {
                $.Notification.error(result.Message);
            }
        }
    });
}

Functions to get all the values from the another API to Edit the status with the previous API:

$dataTable.on("click", "a.edit", function () {
    var $this = $(this);
    $.ajax({
        type: "GET",
        url: "/Mailbox/GetMailboxById/" + $this.data('id'),
        error: (result) => $.Notification.error(result),
        success: function (result) {
            if (result.Success) {
                var mymailbox = result.Mailboxes[0];
                $(FormMB.Id).val(mymailbox.Id);
                $(FormMB.MailboxStatus).val(mymailbox.MailboxStatus);
                LoadMailboxStatus();
            }
            else {
                $.Notification.error(result.Message);
            }
        }
    });

    $mailboxModal.modal();
});
14
  • It's not clear what you are asking?
    – akaBase
    Apr 6, 2020 at 16:23
  • var status = result.Statuses; should be var status = result. statuses;
    – hoangdv
    Apr 6, 2020 at 16:24
  • @hoangdv yes, but in Postman, is statuses
    – victcdva
    Apr 6, 2020 at 16:30
  • @victcdva The problem solved? Right?
    – hoangdv
    Apr 6, 2020 at 16:32
  • @akaBase just get the selected value from the dropdown in the view, the view is filled with the API but always take the status like: value 0 when I do the POST
    – victcdva
    Apr 6, 2020 at 16:33

2 Answers 2

1
+50

You need to pass value you want to select to LoadMailboxStatus method

$dataTable.on("click", "a.edit", function () {
//...
$(FormMB.Id).val(mymailbox.Id);
$(FormMB.MailboxStatus).val(mymailbox.MailboxStatus);

//change here
//LoadMailboxStatus();
LoadMailboxStatus(mymailbox.MailboxStatus);
//....

and:

function LoadMailboxStatus(selectedName) {
    var dropDown = $("#Status");
    dropDown.empty();

    $.ajax({
        type: "GET",
        url: "/Mailbox/GetStatuses/",
        error: (result) => $.Notification.error(result),
        dataType: 'json',
        success: function (result) {
            if (result.Success) {
                var status = result.Statuses;
                $.each(status, function (key, item) {
     dropDown.append($('<option></option>').attr('selected',(item.Name == selectedName) ? 'selected' : undefined).attr('value', item.Id).text(item.Name));

/*
                    dropDown.append($('<option></option>').attr('value', item.Id).text(item.Name));
                    $('option', this).each(function () {
                        if ($(this).html() == item.Name) {
                            $(this).attr('selected', 'selected')
                        };
                    });
*/
                })
            }
            else {
                $.Notification.error(result.Message);
            }
        }
    });
}
0
0

The main issue is with this:

const dropDown = $("#Status")
dropDown.empty()

const Statuses = [
  { "Id": 1, "Name": "Nuevo"    },
  { "Id": 2, "Name": "Leído"    },
  { "Id": 3, "Name": "Atendido" },
]

$.each(Statuses, function (key, item) {
  dropDown.append($('<option></option>').attr('value', item.Id).text(item.Name))
  console.log("wrong this",  this)
  console.log("no <option>'s found", $('option', this).length)
  console.log("<option>'s found with correct this", $('option', dropDown).length)
  // should be $('option', dropDown), but let it be for now
  $('option', this).each(function () {
    console.log("never called!!!")
    // ...
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select class="form-control select2" data-toggle="select2" id="Status" name="Status"></select>

Let's try again with correct this

const dropDown = $("#Status")
dropDown.empty()

const Statuses = [
  { "Id": 1, "Name": "Nuevo"    },
  { "Id": 2, "Name": "Leído"    },
  { "Id": 3, "Name": "Atendido" },
]

$.each(Statuses, function (key, item) {
  dropDown.append($('<option></option>').attr('value', item.Id).text(item.Name))
  $('option', dropDown).each(function (i, el) {
    console.log("condition =", $(this).html() == item.Name)
    console.log("tring to select", $(this).html(), i)
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select class="form-control select2" data-toggle="select2" id="Status" name="Status"></select>

So what exactly are you trying to select? Right now your are trying to select the last the options in sequence, and you are doing it thrice. (But of cause your original code never gets to this point)

Should be:

const dropDown = $("#Status")
dropDown.empty()

const Statuses = [
  { "Id": 1, "Name": "Nuevo"    },
  { "Id": 2, "Name": "Leído"    },
  { "Id": 3, "Name": "Atendido" },
]

// some condition you must choose by yourself
function condition(item) { return item.Id === 2 }

$.each(Statuses, function (key, item) {
  const option = $('<option></option>').attr('value', item.Id).text(item.Name)
  dropDown.append(option)
  if(condition(item)) option.attr('selected', 'selected')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select class="form-control select2" data-toggle="select2" id="Status" name="Status"></select>

6
  • The value is not selected yet
    – victcdva
    Apr 7, 2020 at 17:47
  • Is this a question or just confirmation that everything is fine now?
    – x00
    Apr 7, 2020 at 18:12
  • nope, when I implement what you put in, the value is not selected
    – victcdva
    Apr 7, 2020 at 18:46
  • What value? As you can see in the last code snippet Leido (the value I decided to select) is successfully selected. As I said, in your code there is nothing about the value you want to choose. More precisely, the condition you've wrote if ($(this).html() == item.Name) { does nothing - it is always true.
    – x00
    Apr 8, 2020 at 7:14
  • ...always true for the last added <option>. Updated the second snippet to show it
    – x00
    Apr 8, 2020 at 7:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.