Reputation: 1585
Since I want to get the companyTitle
when a user selects something from the dropdown menu. I have defined it like this data-description="${companyTitle}"
as shown in the code below of the success function of my Ajax call.
success : function(data) {
$.each(data.personnelData.reverse(), function (i) {
let companyId = data.personnelData[i].companyId;
let companyTitle = data.personnelData[i].title;
let dateOfCreation = moment(data.personnelData[i].createDate).format('MM/DD/YYYY');
$("#myList").append(`<option data-description="${companyTitle}" value="${companyId}">${companyTitle}|${dateOfCreation}</option>`);
});
},
When I tested it like this in my javascript code:
$("select#myList").change(function(){
console.log("Testing companyTitle");
console.log($('#myList :selected').data('description'));
})
I only saw the following in the console log - Company Set for
And I believe it is because of the following:
When I inspected the option tag in the browser, It showed me the following entry:
<option data-description="Company Set for " abc="" pxy="" psqrty@12:20:49"="" (4="" companies="" on="" 09="" 22="" 2020="" 01:20:53="" pm)"="" value="12345">Company Set for "Abc Pxy Psqrty@12:20:49" (4 companies on 09/22/2020 01:20:53 PM)|09/22/2020</option>
How can I fix this so that inside $("select#myList").change(function(){
I can retrieve only the part inside the double quotes (i.e. Abc Pxy Psqrty@12:20:49
) of the following companyTitle
:
Company Set for "Abc Pxy Psqrty@12:20:49" (4 companies on 09/22/2020 01:20:53 PM)
Upvotes: 1
Views: 47
Reputation: 943
When data in the data.personnelData[i].title
always similar and has only one pair of double quotes you can split that string like:
var companyTitle = "Company Set for \"Abc Pxy Psqrty@12:20:49\" (4 companies on 09/22/2020 01:20:53 PM)";
var companyTitleDescription = companyTitle.indexOf('"') > -1 ? companyTitle.split("\"")[1] : companyTitle;
console.log(companyTitleDescription);
and assign that to your data-description
attribute.
Upvotes: 0
Reputation: 136074
If rather than building your option
using string concatenation, you build it using jQuery's object model the description data does not get garbled because of the quotes:
const companyTitle = "Company Set for \"Abc Pxy Psqrty@12:20:49\" (4 companies on 09/22/2020 01:20:53 PM)",
companyId = 1,
dateOfCreation = "01/01/2020";
const $option = $('<option />')
.val(companyId)
.text(`${companyTitle}|${dateOfCreation}`)
.data('description',companyTitle);
$('#myList').append($option);
$('#myList').on('change', function(){
console.log($(":selected", this).data('description'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myList">
<option>Select</option>
</select>
If you then want to extract just the bit in quotes that should be fairly straightforward - use regex or string manipulation. There are plenty of examples of extracting the value between quotes.
Upvotes: 1