This question already has an answer here:
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 )?>" + " - ";
</div>
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;