0

I have a multiple select input:

<select name="empleados[ ]" id="empleados" class="form-control inputstl"  onChange="getSelectedOptions(this)" multiple>
<option value=""></option>

I want to show on a div the selected items:

<div id="lista"></div>

I am getting the selected items with function getSelectedOptions(this):

<script>

function getSelectedOptions(sel) {
  var opts = [],
    opt;
    var div = document.getElementById('lista');
     div.innerHTML = "";
  var len = len = sel.options.length;
  for (var i = 0; i < len; i++) {

    opt = sel.options[i];

    if (opt.selected) {
      opts.push(opt);


      div.innerHTML =  div.innerHTML +  opt.value + " - ";
    }
  }

  return opts;
}
</script>

It is working fine. But I need to translate the returned values.

For example, the returned array is : 567 - 858 - 363

I have an external PHP function that receive the id number and returns a name.

The function is: get_nombre($id).

How can I insert the PHP function inside JS?

I have tried as follows, but throws an error:

div.innerHTML =  div.innerHTML + " <?php echo get_nombre(?> opt.value<?php )?>" + " - ";
mvasco
  • 4,965
  • 7
  • 59
  • 120
  • you can't use php code inside javascript you have to use ajax – JYoThI Mar 13 '17 at 07:23
  • You cannot use php on the client side, so inside javascript, since php (usually) is operated in the server side, so in a different system. – arkascha Mar 13 '17 at 07:23
  • You can try to make a single ajax request per ID to translate it, but that is not very effective. Can't you resolve those IDs before returning the result to the initial ajax request? – arkascha Mar 13 '17 at 07:24
  • Alternatively, you could include the name as a data attribute on the option if that's possible. – Rwd Mar 13 '17 at 07:25
  • 1
    name – JYoThI Mar 13 '17 at 07:29
  • @JYoThI, thank you good alternative. – mvasco Mar 13 '17 at 07:34

1 Answers1

1

I'm pretty sure, you dont need PHP at this point, because options should already have a text, which could be used.

function getSelectedOptions(sel) {
  var opts = [],
    opt;
    var div = document.getElementById('lista');
     div.innerHTML = "";
  var len = len = sel.options.length;
  for (var i = 0; i < len; i++) {

    opt = sel.options[i];

    if (opt.selected) {
      opts.push(opt);


      div.innerHTML =  div.innerHTML +  opt.text + " - ";
    }
  }

  return opts;
}

If the inner text of the option don't contain the text you want, you could also use data attributes and add the desired text to them.

<option value="someid" data-text="text">other text</option>

and with javascript

var text = opt.dataset.text;
Philipp
  • 15,377
  • 4
  • 35
  • 52