click to replace value, shift + click to append value using jquery

空扰寡人 提交于 2020-01-16 17:28:43

问题


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


回答1:


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




回答2:


$('ul#filter-results').on('click', 'li', function(e) {
  if(e.shiftKey) {
    do something;
  } else {
    do something else;
  }
});



回答3:


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.




回答4:


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...



来源:https://stackoverflow.com/questions/11468644/click-to-replace-value-shift-click-to-append-value-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!