0

The complete code is available on this link

I have a form that has one dropdown and an input field. The dropdown allows a user to select multiple values and these selected values are displayed in the input field. This input field not only displays the selected values but also allows the user to type their own message.

Now there are 2 issue

First is that when I fetch the value at the backend, I am not able to differentiate the selected value that are displayed inside the input box and the message typed by the user inside the same input box.

Second issue is if i select random values from the dropdown, then inside the input box that displays those values has multiple comma between 2 values

The view comes something like this

enter image description here

HTML Code

<form  id="send_parent">
  <select id='rec' name="rec " class="selectpicker" multiple >
    <option value="1" >A</option>
    <option value="2" >B</option>
    <option value="3" >C</option>
    <option value="4" >D</option>
    <option value="5" >E</option>
    <option value="6" >F</option>
  </select>

   <input type="text" name="msg" id="msg">

   <button type="submit" id="save">SAVE</button>
</form>

Script Code

$("#rec").on("change",function(){
    update();
});

function update() {
    var selected=[];
    $('#rec option:selected').each(function()
    {
        selected[$(this).val()]="@"+$.trim($(this).text());
    });
 $("#msg").val(selected);
}



 $("#send_parent").submit(function() 
   {
     var formData = new FormData();
     formData.append('rec', rec.value);
     formData.append('msg', msg.value);
     jQuery.ajax(
      {
        type: "POST",
        url: "<?php echo base_url(); ?>" + "value/send_value",
        data: formData,
        processData: false,
        contentType: false,
        success: function(res) 
          {
              console.log(res);
          },
        error: function(errResponse) 
          {
           console.log(errResponse);
          }
     });
     return false;

 });       
Sam
  • 1,381
  • 4
  • 30
  • 70

2 Answers2

0

For issue 2 you want to do something like

$("#msg").val(selected.join(','));

Note: text inputs can store only strings, the browser will convert the data you provide to a string

For issue 1 your ajax success function just consoles the result

madalinivascu
  • 32,064
  • 4
  • 39
  • 55
0

As you passed the selected values to the input pass it to a new array and you will have the selected values , to separate it from user input you can do the following: var textInput= document.getElementById("msg").value; var userInput = textInput.replace(selectedValuesArray,'');
This for the first issue. And for the second issue to remove the duplicate in commas please check this topic: Remove duplicate commas and extra commas at start/end with RegExp in JavaScript, and remove duplicate numbers?

Hassan Kandil
  • 1,612
  • 1
  • 13
  • 26