-1

Am making an select option from ajax success. The problem is that, the results are array so i need to manipulate the array with some html.

My appending code:

data = [['2022-02-01', '2022-02-02'],['2022-03-01', '2022-03-02'],['2022-04-01', '2022-04-02']]

$("#id_course").change(function () {
     $('select[id=id_intakes]').empty().prepend("<option></option>");
     $.each(data, function(index, date){
          $('select[id=id_intakes]').append(
              $('<option></option>').attr("value",date).text(date)
          )
    });
})

Just creates the select correctly, but it displays the array as it is. The dropdown contains all the three values array

['2022-02-01', '2022-02-02']
['2022-03-01', '2022-03-02']
['2022-04-01', '2022-04-02']

I need to manipulate this like

From:2022-02-01 & To:2022-02-02
From:2022-03-01 & To:2022-03-02
From:2022-04-01 & To:2022-04-02

So how to do this ?

  • `.text("From:"+date[0]+" & To:"+date[1]+"")` ...? And maybe the same for the value, depending on what exactly you want the submission value to be. – CBroe Feb 17 '22 at 07:09
  • Basic array access and string concatenation. Read the documentation, please. [Text formatting](//developer.mozilla.org/docs/Web/JavaScript/Guide/Text_formatting), [Referring to array elements](//developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#referring_to_array_elements). – Sebastian Simon Feb 17 '22 at 07:11

1 Answers1

0

You can add this to your code:

name = `From:${name[0]} & To:${name[1]}`;

Demo

data = [
  ['2022-02-01', '2022-02-02'],
  ['2022-03-01', '2022-03-02'],
  ['2022-04-01', '2022-04-02']
]

$('select#id_intakes').empty().prepend("<option></option>");
$.each(data, function(index, name) {
  name = `From:${name[0]} & To:${name[1]}`;
  $('select[id=id_intakes]').append(
    $('<option></option>').attr("value", name).text(name)
  )
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="id_intakes"></select>
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77