I want to provide tagging like feature in my text-box, following through Stackoverflow I downloaded and added http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js file in my ASP.NET web folder and I am able to use all of its function through my js function.
The problem I am suffering with is because of an event( focusout ) in my js code , At current I need to make an on('focusout') event to add a tag in my search box. I've added HTML and CSS code also, and they are just fine, my problem is with Javascript code
Code:
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="tags">
<input type="text" id="search" />
</div>
</body>
</html>
CSS:
#tags{
float:left;
border:1px solid #ccc;
padding:5px;
font-family:Arial;
}
#tags span.tag{
cursor:pointer;
display:block;
float:left;
color:#000;
background:#eee;
padding:5px;
padding-right:25px;
margin:4px;
}
#tags span.tag:hover{
opacity:0.7;
}
#tags span.tag:after{
position:absolute;
content:"x";
border:1px solid;
padding:0 4px;
margin:3px 0 10px 5px;
font-size:10px;
}
#tags input{
background:#fff;
border:0;
margin:4px;
padding:7px;
width:auto;
}
#search{
background:#fff;
border: 0px;
width:auto;
height:auto;
}
JS:
$('#tags input').on('focusout',function(){
var txt= $.trim( $(this).val() );
if(txt){
$("#search").before('<span class="tag">'+txt+'</span>');
}
$(this).prop('value','');
});
$('#tags').on('click','.tag',function(){
$(this).remove();
});
Problem:
I don't want my user to click outside everytime user wants to add a tag, I want to make it rather easier with a key combination of
Ctrl
+Enter
. How can I do that ?
Replace your focusout
event with a keydown
event:
$('#tags input').keydown(function (e) {
if(e.ctrlKey && e.keyCode == 13) {
var txt= $.trim( $(this).val() );
if(txt){
$("#search").before('<span class="tag">'+txt+'</span>');
}
$(this).prop('value','');
}
});
Explanation: You check your Event
object to see if ctrl key was pressed:
if(e.ctrlKey
And checking what was pressed at the same time (13 is the keycode for Ctrl ):
if(e.ctrlKey && e.keyCode == 13) {
If both statements are true, then you can assume your user has pressed the Ctrl + Enter combination.
JSFiddle Demo: http://jsfiddle.net/losnir/FxQ62/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.