Reputation: 1583
I have the following AJAX call and right now I have the description
, name
and id
of the company in the dropdown menu.
I am wondering if I can hide something like data.company[i].id
. This will be hidden from the UI but I still want it because when a user selects a project, I am grabbing the id in my other logic.
$.ajax({
url: 'myurl',
type: 'GET',
dataType: 'json',
success: function(data) {
$.each(data.company, function(i) {
$("#mylist").append('<option>' + data.company[i].description + ' | ' + data.company[i].name + ' | ' + data.company[i].id + '</option>');
});
},
error: function(request, error) {
$.growl.error({
title: "Error",
message: "Webservice request failed!"
});
}
});
Upvotes: 1
Views: 67
Reputation: 2131
You can set the value.
$.ajax({
url: 'myurl',
type: 'GET',
dataType: 'json',
success: function(data) {
$.each(data.company, function(i) {
var optData = data.company[i].description;
var optText = data.company[i].name;
var optValue = data.company[i].id;
$("#mylist").append(`<option data-description="${optData}" value="${optValue}">${optText}</option>`);
});
},
error: function(request, error) {
$.growl.error({
title: "Error",
message: "Webservice request failed!"
});
}
});
To get the currently selected value:
$('#mylist').val();
To get the currently selected text:
$('#mylist :selected').text();
To get the currently selected data:
$('#mylist :selected').data('description');
Upvotes: 1
Reputation: 337733
If you want to hide a value from the UI but retain it so you can use it in your logic, try using a data
attribute on the element. This is not visible to the users, but can be read back out when the option is selected.
Here's a basic example:
let data = {
company: [{
description: 'Desc #1',
name: 'Name #1',
id: 'Id #1'
},{
description: 'Desc #2',
name: 'Name #2',
id: 'Id #2'
},{
description: 'Desc #3',
name: 'Name #3',
id: 'Id #3'
}]
}
let options = data.company.map(company => `<option data-id="${company.id}">${company.description} | ${company.name}</option>`);
$('#mylist').append(options).on('change', e => {
let id = $(e.target).find('option:selected').data('id');
console.log(e.target.value, id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mylist"></select>
Upvotes: 1