How to convert select2
array output to single string (separated by comma)? Just like this "task_owner":"Administrator,abc2"
. Current output is separated by comma but in single array "task_owner":["Administrator","abc2"]
. This is because the DB is received by string, not array.
Another question, how to re-convert back to array since during editing, Ajax will send that String from DB and I maybe need to convert back to Array for display purpose.
I was referred to this Link but not working.
<form id="myForm">
<select type="text" class="form-control myClass" id="myID" multiple="multiple"></select>
</form>
$('.myClass').select2({
tags: true
});
$('#btnSubmit').on('click',function(){
var testOutput = ""; // I put this because an error appear so I create a new var but the output is = "null", why?
var owner = $('#myID').val();
if (owner.val() !== null && owner.val().length > 0){
var testOutput = $('#myID') = owner.val().join(',');
testOutput = Object.assign({}, {task_owner: testOutput.task_owner.join(",")})
}
// parameter that need to send to API
var obj = {
task_owner : testOutput,
// Another parameter...
};
var params = JSON.stringify(obj);
$.ajax({
// My Ajax Condition...
});
});
As dicussed:
$(".myClass").select2({
tags: true
});
$("#btnSubmit").on("click", function() {
var testOutput = ""; // I put this because an error appear so I create a new var but the output is = "null", why?
var owner = $("#myID").val(); //
if (Array.isArray(owner) && owner.length) {
testOutput = owner.join(",");
}
var obj = {
task_owner: testOutput
};
var params = JSON.stringify(obj);
$.ajax({
// My Ajax Condition...
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.