How to add text to a text area

0

My problem is not a problem, it is a doubt.

I have a text area in which the user writes a comment that will be published on my website, but I also have a command code that by pressing, for example / in the text area, a list with friends is displayed of the user to tag it in said comment similar to the @ when you are going to tag someone in fb, instagram etc ..

So far, what I do not know how to do is when that list of users unfolds (as you know you have to click on the user you want), tag in that comment so that the name of that user too is added to the text area. Then in the submit, save the information in the database with the comment and the person tagged in that comment.

How would that be done? I will leave my code of what I am doing. I would appreciate any help or tips about my doubt. Thanks !.

tag.php

<div>
  <form id="tagcoment" action="tagcoments.php" method="post">
    <h2 class="texto">write your coment</h2>

  <div class="input-group col-12" >
   <div id="myUsers" style="display:none;"></div>
    <textarea><textarea>
    </div>

  </form>

</div>

tag.js

$(document).ready(function() {

  $('#tagcoment textarea').on('keypress', function() {

    var target=$(this).val()//obtenemmos lo escrito en el textarea

    if(target.substr(0,1)=="/"){//si del 0 al 1 es igual al comando / buscar amigos

      var target= target.substr(2);//enviamos es texto despues del comando /
    $.ajax({
      type: "POST",
      url:tagcoments.php,
      data:{target:target},

      success: function(response) {

          $("#myUsers").slideDown("fast").html(response);
        }
       });
     }   
   });  
});

tagcoments.php

 <?php

   session_start();
   include"conexion.php";
 $target=mysqli_real_escape_string($conexion,$_POST["target"]);//obtenemos lo escrito 
 $my=$_SESSION["id"];

$sql=mysqli_query($conexion,"SELECT foto,nombre,apellido FROM
registro r
INNER JOIN amigos a ON r.id=a.para 
WHERE a.de='$my' AND r.nombre like '%$target%' ");//esta consulta me devuelve mis amigos segun el texto que vaya introduciendo

while($row=mysqli_fetch_array($sql)){ ?>
<!--imprimimos amigos segun el texto-->
 <div>
  <a href="">  <img src="imagenes/<?php echo$row["foto"]?>"><?php   $row["nombre"]." ".$row["apellido"]?>  </a>
 </div>

As you can see, the code is very simple, everything works but besides that I want that at the time of the list of friends to unfold that when I click on one of those friends I add the name of that friend to the textarea as I told you, it's something similar to the @ commands.

    
asked by andy gibbs 01.08.2018 в 16:25
source

2 answers

2

First : instead of checking if the text starts with a slash, you should use a regular expression to search for the slash anywhere in the textarea.

var target=$(this).val();//obtenemmos lo escrito en el textarea
var match = /\/(\w+)/.exec(target);

This is: 'look for a slash followed by one more characters'. If the verification is satisfied, then match[1] will contain the fragment of the name to be searched.

Second , you should use the keyup event to detect when the first letter has been entered after the slash. Otherwise, if you write: /a you will need to write another letter so that it is fulfilled that there is indeed something after the slash.

Third : when you get the substring, you execute the search (in my example, in the absence of ajax, I replaced the behavior using a function that returns a promise, which is resolved with friends that start with the substring)

Fourth : When the promise of the search is resolved and you receive a list of possible friends, a function is called:

  • Take your div #myUsers that is originally hidden with a class
  • If there are friends that fit, it takes from the div the class that hides it.
  • For each friend, add an element a with class amigo to the container

In your case, the event success of your ajax call already returns the html of the friends, so you only have to verify that it does not come empty and in that case remove the class invisible to #myUsers .

Fifth : You declare a listener elsewhere that says:

  • By clicking on one of the a , within #myUsers , the occurrence of /texto_parcial with @nombre_amigo in textarea is replaced
  • The class hiding #myUsers is added again.

Why replace with an @? Basically because I do not want the slash to trigger the search again. When changing it with an @ it becomes a chain without special meaning.

var amigos=['alejandro','alberto','alfredo','pedro','pepe'];

function buscarAmigos(empiezacon) {
   
   return new Promise(function(resolve,reject) {
       resolve(amigos.filter(function(amigo) {
          return amigo.indexOf(empiezacon)===0;
       }));
   });

}

function llenarAmigos(posiblesamigos) {
  jQuery('#myUsers').empty();
  if(!posiblesamigos.length) {
    jQuery('#myUsers').addClass('invisible');
    return;
  }
  posiblesamigos.forEach(function(amigo) {
      jQuery('#myUsers').append('<a class="amigo">'+amigo+'</a>');
  });
  jQuery('#myUsers').removeClass('invisible');
}

$(document).ready(function() {

  $('#tagcoment textarea').on('keyup', function() {

    var target=$(this).val();//obtenemmos lo escrito en el textarea

    
     var match = /\/(\w+)/.exec(target);
     if(match!==null) {
     
       buscarAmigos(match[1]).then(function(posiblesamigos) {
           llenarAmigos(posiblesamigos);
       });
     
     }
     
   });  
   $('#tagcoment textarea').on('click', function() {
      llenarAmigos([]);
   });  

  jQuery('#myUsers').on('click','.amigo',function() {
      var nombre_amigo=jQuery(this).text(),
          texto_mensaje = $('#tagcoment textarea').val();
      
      var match = /\/(\w+)/.exec(texto_mensaje);
      if(match[1]) {
         $('#tagcoment textarea').val(texto_mensaje.replace('/'+match[1], '@'+nombre_amigo));
      }
      llenarAmigos([]);
      
  });
});
textarea {
width:95%;
height:200px;
}
.invisible {
  display:none;
}
#myUsers {
  position:absolute;
  right:20px;
  top:40px;
  width:100px;
  background:white;
  border:1px solid blue;
  padding:10px;
}
#myUsers .amigo {
 border:1px dashed #ccc;
 margin:2px;
 padding:2px;
 display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <form id="tagcoment" action="tagcoments.php" method="post">
    <h2 class="texto">write your coment</h2>

  <div class="input-group col-12" >
   <div id="myUsers" class="invisible"></div>
    <textarea></textarea>
    </div>

  </form>

</div>

Try typing /al anywhere in the textarea.

PS: basically, the same as you have now but adding the class amigo to each link that you return from the backend, and declaring a listener for when you click on a link with class amigo .

    
answered by 01.08.2018 / 19:12
source
0

At the moment of selecting the person you want to tag, save your identifier in an input, div or as best suits, if there are several save it delimited by dashes, bars or commas. Once all this process is well just send it to the comments table where you should have a field 'personasteiquetadas', good luck with your project.

    
answered by 01.08.2018 в 16:44