I have this code.

<select class="select"> <option value="1">Один</option> <option value="2">Два</option> <option value="3">Три</option> <option value="4">Четыре</option> <option value="5">Пять</option> <option value="6">Шесть</option> </select> 

And there is an input in which there may be text, but it is better not to touch it, but at the same time add the value from select .

How to implement it with JS? Started with this:

 $('input').val($('input').val() + $('.select option:selected').val()); 

On this and finished ..

Get out.

  • $('.select').val() - Igor
  • @Igor, isn't it the way I wrote? I need to get the value from the selected item, and then add it to the existing text of the input. - CbIPoK2513
  • code - in response. - Igor

2 answers 2

 $(function(){ let input = $('#test'), inpVal = input.val(); $('.select').on('change', function(){ input.val(inpVal + $(this).val()); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="select"> <option value="1">Один</option> <option value="2">Два</option> <option value="3">Три</option> <option value="4">Четыре</option> <option value="5">Пять</option> <option value="6">Шесть</option> </select><br /> <input type='text' id='test' value='Текст' /> 

  • What you need, thanks! - CbIPoK2513

 $(document).ready(function(){ $(".select").change(function(){ $('.input').val($('.input').val() + $('.select').val()); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="select"> <option value="1">Один</option> <option value="2">Два</option> <option value="3">Три</option> <option value="4">Четыре</option> <option value="5">Пять</option> <option value="6">Шесть</option> </select> <br/> <input class="input" value="aaa"/> 

  • What is necessary .. But how to make sure that there is only one number in the input? Those. either 1 or 2, not 1234, etc. - CbIPoK2513
  • @ CbIPoK2513, then it should be indicated in the question. We are not telepaths to know this in advance. - user207618
  • @Other, yes, I understand .. I just did not take it into account, sorry. - CbIPoK2513