Bartosz
Bartosz

Reputation: 13

How to get specific value from option select - json object

I am trying to extract data from the option value. For example only ID or UserName. Can you please help?

$(document).ready(function() {
  $.getJSON("http://localhost:8080/EBCargoAndCommodityServices/resources/user-form/retrieve", function(data) {
    data.forEach(function(dt) {
      $("#customer-list").append('<option value="' + dt.id + dt.contactName + '">' + dt.contactName + '</option>');
    });
    $('#customer-list').change(function() {
      var str = this.value;
      alert(str);
    });
  });
});

Upvotes: 1

Views: 629

Answers (2)

giovanni
giovanni

Reputation: 388

Sure you can, the best way would be to store the values you need to use into specific data attributes, then access them using the .data() method

    const $ = jQuery;
    $(document).ready(function() {
        // Mocked data for test
        const data = [{"address":"","companyName":"","contactName":"ghkkkkk","email":"","id":22,"surname":"","telephone":0},
        {"address":"","companyName":"","contactName":"asdasd","email":"","id":23,"surname":"","telephone":0}]
        data.forEach(function(dt) {
          $("#customer-list").append('<option data-id="' + dt.id + '" data-name="' + dt.contactName + '" value="' + dt.id + dt.contactName + '">' + dt.contactName + '</option>');
        });
        $('#customer-list').change(function() {
          const selected = $(this).find('option:selected');
          $('#result').text('selected id is: ' + selected.data('id') + ' contact name is : ' + selected.data('name'))
          
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <select id="customer-list">
    <option>select an option</option>
  </select>
  <span id="result"></span>

Upvotes: 1

anuragb26
anuragb26

Reputation: 1475

Let's say for example that dt.id = 1 and dt.contactName is Bartosz.
So you would be alerting 1Bartosz in alert(str)

While building up the options do this,

$("#customer-list").append('<option value="' + `${dt.id}_${dt.contactName}` + '">' + dt.contactName + '</option>'); // Using template literals and concatenating both id and contact name using a delimiter `_`

Then, in your change function do this.

const info = str.split('_')
/*
info will be an array  with two elements 
info[0] will be id  i.e. 1
info[1] will be contactName i.e. Bartosz
*/ 

Upvotes: 1

Related Questions