-1

I need a javascript function for my project which will append the selected value on current value. For example, I am using following code

var select = document.getElementById('cmbitems');
var input = document.getElementById('txtprice');
select.onchange = function() {
  input.value = select.value;
}
<select name="cmbitems" id="cmbitems">
    <option value="price1">blue</option>
    <option value="price2">green</option>
    <option value="price3">red</option>
</select>
<input type="text" name="txtprice" id="txtprice" onClick="checkPrice()">

It displays one selected value. I need to append selected value to previously selected value, if I select 'blue' first and then 'green', it should display "blue,green". If I select red after that, it should display "blue,green,red"

Any help would be appreciated, thanks in advance!

athi
  • 1,643
  • 14
  • 26
Upendra Joshi
  • 573
  • 5
  • 15

1 Answers1

1

This will return the selected text as your requested.

var select = document.getElementById('cmbitems');
var input = document.getElementById('txtprice');
select.onchange = function() {
    input.value = input.value + (input.value.length > 0 ? "," : "") + select.options[select.selectedIndex].text
}
<select name="cmbitems" id="cmbitems">
    <option value="price1">blue</option>
    <option value="price2">green</option>
    <option value="price3">red</option>
</select>
<input type="text" name="txtprice" id="txtprice" onClick="checkPrice()">
Carsten Løvbo Andersen
  • 25,262
  • 9
  • 45
  • 70