click to replace value, shift + click to append va

2019-09-18 14:59发布

I have a list with items.
When I click any of these items, I copy its id-value into a form text-field.
Everytime I click, it replaces the value, which is correct by default. But what I would like to add, is a way for the user to hold down a key on their keyboard, and when they then click, they just .append whatever they just clicked into the same form field.

Here's my jQuery-code I'm using for the first/default scenario:

$(function(){
    $('ul#filter-results li').click(function(){  
        var from = $(this).attr('id');  //  get the list ID and
        $('input#search').val(from+' ').keyup();  //  insert into text-field then trigger the search and
        $('input#search').focus();  //  make sure the field is focused so the user can start typing immediately
    });
});

Is there a way to implement some sort of keyboard key-listener?
Something like:

if (e.shiftKey){
    .append('this text instead')
}

haven't tried out to see if shiftKey is even any valid name here

4条回答
迷人小祖宗
2楼-- · 2019-09-18 15:39

There is a jQuery plugin for extended click.

You could try that or see how they have done it and implement it yourself.

ExtendedClick plugin

Hope this helps.

查看更多
混吃等死
3楼-- · 2019-09-18 15:45

shiftKey is of one of the properties of the event object and is valid to be used. try this:

$(document).on('keyup click', function(e){
   if (e.shiftKey) {
       $('input#search').focus()
       $('input#search').val(e.target.id)
   }
})

DEMO

查看更多
The star\"
4楼-- · 2019-09-18 15:58

This is what I ended up with:
I switched over to altKey because shiftKey marked a lot of text when I clicked.
Didn't do anything besides it doesn't look good...

$(function(){
    $('ul#filter-results li').click(function(e){

        var text = $(this).attr('id');  //  get the ID
        var input = $('#search');  //  form field to insert text into

        if (e.altKey){  input.val(input.val()+', '+text+' ').keyup();  }  //  fetch whatever is already there, and add some more
        else {  input.val(text+' ').keyup();  }  //  just replace whatever is already there

        $('#search').focus();

    });
});

Thanks for good suggestions...

查看更多
对你真心纯属浪费
5楼-- · 2019-09-18 16:00
$('ul#filter-results').on('click', 'li', function(e) {
  if(e.shiftKey) {
    do something;
  } else {
    do something else;
  }
});
查看更多
登录 后发表回答