如何在文本区域内添加标签? [英] How to add tags inside Text Area?

查看:177
本文介绍了如何在文本区域内添加标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个HTML表单,我想在其中添加城市的不同位置。首先,我将从下拉列表中选择城市,然后在该城市下,我需要添加其他地名。

I am designing a HTML form in which I want to add different places of the city. First I am going to select the city from the drop down list, then under that city I need to add different place names.

在我的表单中,我想使用类似于在Gmail中撰写电子邮件时所使用的标签,可以在其中添加多个电子邮件。用逗号分隔的任何单词都应显示为标记。

In my form I want to use Tags similar to those which are used while composing Emails in Gmail, where multiple Emails can be added. Any word seperated by comma should appear to be as a tag.

在提交时,每个地名都必须以不同的值存储在数据库中的地方下。

On Submit, each place name must be stored as a different value under the feild "Places" in the database.

推荐答案

在不重写整个插件的情况下,我将仅向您介绍这种事情通常的工作原理。

Without rewriting an entire plugin, I'll just give you the basics on how something like this typically works.

该框不是文本区域,而是div。在div内部,第一个输入没有边框或背景;它基本上是不可见的。输入输入后,该函数将侦听Tab键或逗号字符(仅在下面使用逗号)。如果它获得了这些触发器之一,它将获取输入的值,将其包装在按钮(或其他一些内联元素,例如span)中,并将其添加到div中。最后,它清除输入。我在这里使用按钮是因为您也应该能够删除该元素。

The box isn't a textarea, it's a div. Inside the div there's first an input with no border or background; it's basically invisible. After typing in the input, the function would either listen for a tab key or comma character (just using comma below). If it gets one of those triggers, it takes the value of the input, wraps it in a button (or some other inline element like a span), and prepends it inside the div. Finally, it clears the input. I'm using a button here because you should also be able to remove the element.

使用jQuery只是为了使事情变得更简单。

Using jQuery just to make things easier.

$('#textarea input').on('keyup', function(e){
   var key = e.which;
   if(key == 188){
      $('<button/>').text($(this).val().slice(0, -1)).insertBefore($(this));
      $(this).val('').focus();
   };
});

$('#textarea').on('click', 'button', function(e){
   e.preventDefault();
  $(this).remove();
   return false;
})

#textarea{
  border:1px solid #eee;
}

#textarea input{
  border:none;
  background:none;
  font-size:1.2em;
  padding:6px;
}

#textarea input:focus{
   outline:none;
}

#textarea button{
   border:1px solid #eee;
   background:#f5f5f5;
  margin:4px;
  font-size:1.2em;
  cursor:pointer;
}

#textarea button:after{
   content:"\d7";
   color:red;
   margin-left:2px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="textarea"><input type="text"/></div>

这篇关于如何在文本区域内添加标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆