1

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...
    });
});
7
  • var testOutput = $('#myID') = mySelect.val().join(','); testOutput = Object.assign({}, {task_owner: testOutput.task_owner.join(",")}) Commented Mar 28, 2020 at 9:22
  • hi, inside curly Object.assign({} need to store anything? or just be like that? sorry I am new. Commented Mar 28, 2020 at 9:27
  • just like that! It is to merge 2 object Commented Mar 28, 2020 at 9:31
  • Sorry OR just use var testOutput = $('#myID') = mySelect.val().join(','); testOutput = {task_owner: testOutput.task_owner.join(",")} Commented Mar 28, 2020 at 9:31
  • I don't get the answer, wait I will update my question with proper code and let you know. Commented Mar 28, 2020 at 9:48

1 Answer 1

1

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...
  });
});
Sign up to request clarification or add additional context in comments.

3 Comments

If you are not busy, could you help me again on this? Link
What in now missing??
This posting is completely done, but have another link, just provide above.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.