Programming

캐치 페이스트 입력

procodes 2020. 5. 7. 21:25
반응형

캐치 페이스트 입력


브라우저에 붙여 넣은 입력을 살균하는 방법을 찾고 있는데, 이것이 jQuery와 관련이 있습니까?

나는 지금까지 이것을 생각해 냈습니다.

$(this).live(pasteEventName, function(e) {
 // this is where i would like to sanitize my input
 return false;
}

불행히도이 "사소한"문제로 인해 개발이 크게 진행되었습니다. 누군가가 올바른 방향으로 나를 가리킬 수 있다면 나는 정말로 행복한 캠프로 만들 것입니다.


좋아, 그냥 같은 문제에 부딪쳤다. 나는 먼 길을 갔다

$('input').on('paste', function () {
  var element = this;
  setTimeout(function () {
    var text = $(element).val();
    // do something with text
  }, 100);
});

.val () func이 채워질 때까지 작은 시간 초과.

이자형.


실제로 이벤트 에서 바로 값을 가져올 수 있습니다 . 그래도 도착하는 방법이 조금 모호합니다.

통과하지 않으려면 false를 반환하십시오.

$(this).on('paste', function(e) {

  var pasteData = e.originalEvent.clipboardData.getData('text')

});

크로스 플랫폼 호환성을 위해서는 입력 및 속성 변경 이벤트를 처리해야합니다.

$ (something).bind ("input propertychange", function (e) {
    // check for paste as in example above and
    // do something
})

다음 코드를 사용하여 문제를 해결했습니다.

$("#editor").live('input paste',function(e){
    if(e.target.id == 'editor') {
        $('<textarea></textarea>').attr('id', 'paste').appendTo('#editMode');
        $("#paste").focus();
        setTimeout($(this).paste, 250);
    }
});

이제 캐럿 위치를 저장하고 해당 위치에 추가하면 모든 설정이 완료됩니다.


흠 ... 붙여 넣는 데이터를 잡는 데 사용할 수 있다고 생각 합니다 e.clipboardData. 팬 아웃되지 않으면 여기를 살펴 보십시오 .

$(this).live("paste", function(e) {
    alert(e.clipboardData); // [object Clipboard]
});

붙여 넣기 이벤트를 수신하고 키업 이벤트 리스너를 설정하십시오. 키업시 값을 캡처하고 키업 이벤트 리스너를 제거하십시오.

$('.inputTextArea').bind('paste', function (e){
    $(e.target).keyup(getInput);
});
function getInput(e){
    var inputText = $(e.target).val();
    $(e.target).unbind('keyup');
}

이것은 당신이 원하는 것에 더 가까워지고 있습니다.

function sanitize(s) {
  return s.replace(/\bfoo\b/g, "~"); 
};

$(function() {
 $(":text, textarea").bind("input paste", function(e) {
   try {
     clipboardData.setData("text",
       sanitize(clipboardData.getData("text"))
     );
   } catch (e) {
     $(this).val( sanitize( $(this).val() ) );
   }
 });
});

clipboardData 객체가 발견되지 않으면 (IE 이외의 브라우저에서) 현재 요소의 전체 값 + 클립 보드의 값을 얻습니다.

실제로 데이터가 실제로 요소에 붙여 넣은 후에 만 ​​있다면 입력 전후에 두 값을 나누기 위해 추가 단계를 수행 할 수 있습니다.


How about comparing the original value of the field and the changed value of the field and deducting the difference as the pasted value? This catches the pasted text correctly even if there is existing text in the field.

http://jsfiddle.net/6b7sK/

function text_diff(first, second) {
    var start = 0;
    while (start < first.length && first[start] == second[start]) {
        ++start;
    }
    var end = 0;
    while (first.length - end > start && first[first.length - end - 1] == second[second.length - end - 1]) {
        ++end;
    }
    end = second.length - end;
    return second.substr(start, end - start);
}
$('textarea').bind('paste', function () {
    var self = $(this);
    var orig = self.val();
    setTimeout(function () {
        var pasted = text_diff(orig, $(self).val());
        console.log(pasted);
    });
});

 $('').bind('input propertychange', function() {....});                      

This will work for mouse paste event.


This code is working for me either paste from right click or direct copy paste

   $('.textbox').on('paste input propertychange', function (e) {
        $(this).val( $(this).val().replace(/[^0-9.]/g, '') );
    })

When i paste Section 1: Labour Cost it becomes 1 in text box.

To allow only float value i use this code

 //only decimal
    $('.textbox').keypress(function(e) {
        if(e.which == 46 && $(this).val().indexOf('.') != -1) {
            e.preventDefault();
        } 
       if (e.which == 8 || e.which == 46) {
            return true;
       } else if ( e.which < 48 || e.which > 57) {
            e.preventDefault();
      }
    });

$("#textboxid").on('input propertychange', function () {
    //perform operation
        });

It will work fine.


document.addEventListener('paste', function(e){
    if(e.clipboardData.types.indexOf('text/html') > -1){
        processDataFromClipboard(e.clipboardData.getData('text/html'));
        e.preventDefault();

        ...
    }
});

Further:


See this example: http://www.p2e.dk/diverse/detectPaste.htm

It essentialy tracks every change with oninput event and then checks if it’s a paste by string comparison. Oh, and in IE there’s an onpaste event. So:

$ (something).bind ("input paste", function (e) {
    // check for paste as in example above and
    // do something
})

This method uses jqueries contents().unwrap().

  1. First, detect the paste event
  2. Add a unique class to the tags that are already in the element into which we are pasting.
  3. After a given timeout scan through all the contents unwrapping tags that don't have the class that you set earlier. Note: This method does not remove self closing tags like
    See an example below.

    //find all children .find('*') and add the class .within .addClass("within") to all tags
    $('#answer_text').find('*').each(function () {
    $(this).addClass("within");
    });
    setTimeout(function() {
    $('#answer_text').find('*').each(function () {
        //if the current child does not have the specified class unwrap its contents
        $(this).not(".within").contents().unwrap();
    });
    }, 0);
    

This proved to be quite illusive. The value of the input is not updated prior to the execution of the code inside the paste event function. I tried calling other events from within the paste event function but the input value is still not updated with the pasted text inside the function of any events. That is all events apart from keyup. If you call keyup from within the paste event function you can sanitize the pasted text from within the keyup event function. like so...

$(':input').live
(
    'input paste',
    function(e)
    {
        $(this).keyup();
    }
);

$(':input').live
(
    'keyup',
    function(e)
    {
        // sanitize pasted text here
    }
);

There is one caveat here. In Firefox, if you reset the input text on every keyup, if the text is longer than the viewable area allowed by the input width, then resetting the value on every keyup breaks the browser functionality that auto scrolls the text to the caret position at the end of the text. Instead the text scrolls back to the beginning leaving the caret out of view.


Script to remove special characters from all fields with class portlet-form-input-field:

// Remove special chars from input field on paste
jQuery('.portlet-form-input-field').bind('paste', function(e) {
    var textInput = jQuery(this);
    setTimeout(function() {
        textInput.val(replaceSingleEndOfLineCharactersInString(textInput.val()));
    }, 200);
});

function replaceSingleEndOfLineCharactersInString(value) {
    <%
        // deal with end-of-line characters (\n or \r\n) that will affect string length calculation,
        // also remove all non-printable control characters that can cause XML validation errors
    %>
    if (value != "") {
        value = value.replace(/(\x00|\x01|\x02|\x03|\x04|\x05|\x06|\x07|\x08|\x0B|\x0C|\x0E|\x0F|\x10|\x11|\x12|\x13|\x14|\x15|\x16|\x17|\x18|\x19|\x1A|\x1B|\x1C|\x1D|\x1E|\x1F|\x7F)/gm,'');
        return value = value.replace(/(\r\n|\n|\r)/gm,'##').replace(/(\#\#)/gm,"\r\n");
    }
}

There is one caveat here. In Firefox, if you reset the input text on every keyup, if the text is longer than the viewable area allowed by the input width, then resetting the value on every keyup breaks the browser functionality that auto scrolls the text to the caret position at the end of the text. Instead the text scrolls back to the beginning leaving the caret out of view.

function scroll(elementToBeScrolled) 
{
     //this will reset the scroll to the bottom of the viewable area. 
     elementToBeScrolled.topscroll = elementToBeScrolled.scrollheight;
}

참고URL : https://stackoverflow.com/questions/686995/catch-paste-input

반응형