-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,683
  • 15
  • 26
Upendra Joshi
  • 603
  • 6
  • 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
  • 26,637
  • 10
  • 47
  • 77