How to copy input of type date if there is no choice?

I have a simple input:

<input type="date" class="self-select" value="1980-05-04">
<input type="text" class="self-select" value="my birthday">

And I have a listener for all of these inputs:

$(document).on('focus', '.self-select', function(){
    $(this).select();
});

The idea is that when the user clicks on the input field, its contents are selected, so he just needs to copy ctrl + c.

But this does not work with type="date"in Chrome. There is no choice and, in principle, there is no way to copy the date value from the input field.

Here is the fiddle: https://fiddle.jshell.net/Dmatafonov/s8r9dt6j/

+4
source share
2 answers

I managed to write some kind of "hacker" walk ...

, ( SO), "" CTRL + C keydown...

, ...
, , .
.

enter image description here

, .
!

// Your on focus -> select event handler
$(document).on('focus', '.self-select', function(){
    $(this).select();
});



// An on keydown event handler to copy to clipboard when [ctrl]+[C] is pressed
// Exclusively for the "date" inputs.
$(document).on('keydown', 'input[type="date"]', function(e){

    if( e.which == 67 && e.ctrlKey ){
        var copiedDate = $(this).val();
        //console.log( copiedDate );

        // First, get the value and fix the date format from YYYY-MM-DD to MM/DD/YYYY

        var tempDate = copiedDate.split("-");
        var year = tempDate.shift();
        //console.log( year );
        tempDate.push(year);
        var fixedDate = tempDate.join("/");
        console.log( fixedDate );

        // Then temporarly change the input type from "date" to "text"

        $(this).attr("type","text").val(fixedDate);


        // Use the copy to clipboard function
        $(this).select();
        copyToClipboard($(this));

        // Set the input type back to "date" a small delay later
        var that=$(this);
        setTimeout(function(){
            that.attr("type","date").val(copiedDate);  // And restore original value
        },20)
    }
});

// ---------------------------------
// A nice JavaScript "copy to clipboard" function found here : /questions/4036/click-button-copy-to-clipboard-using-jquery/35480#35480
// ---------------------------------

function copyToClipboard(elem) {
    // create hidden text element, if it doesn't already exist
    var targetId = "_hiddenCopyText_";
    var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
    var origSelectionStart, origSelectionEnd;
    if (isInput) {
        // can just use the original source element for the selection and copy
        target = elem;
        origSelectionStart = elem.selectionStart;
        origSelectionEnd = elem.selectionEnd;
    } else {
        // must use a temporary form element for the selection and copy
        target = document.getElementById(targetId);
        if (!target) {
            var target = document.createElement("textarea");
            target.style.position = "absolute";
            target.style.left = "-9999px";
            target.style.top = "0";
            target.id = targetId;
            document.body.appendChild(target);
        }
        target.textContent = elem.textContent;
    }
    // select the content
    var currentFocus = document.activeElement;
    //target.focus();
    target.setSelectionRange(0, target.value.length);

    // copy the selection
    var succeed;
    try {
        succeed = document.execCommand("copy");
    } catch(e) {
        succeed = false;
    }
    // restore original focus
    if (currentFocus && typeof currentFocus.focus === "function") {
        currentFocus.focus();
    }

    if (isInput) {
        // restore prior selection
        elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    } else {
        // clear temporary content
        target.textContent = "";
    }
    return succeed;
}
/* Textarea sizing for this snippet */
#pasteIt{
    width:316px;
    height:150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="date" class="self-select" value="1980-05-04">
<input type="text" class="self-select" value="my birthday">
<br>
<br>
<textarea id="pasteIt" placeholder="Paste here to test your clipboard."></textarea>
Hide result
+1

, . - , , .

datetime-local.

https://jsfiddle.net/h444uL45/23/

var control_pressed = false;

function changeInputType(oldObject, oType) {
  var newObject = document.createElement("input");
  newObject.type = oType;
  if(oldObject.size) {newObject.size = oldObject.size;}
  if(oldObject.value) {newObject.value = oldObject.value;}
  if(oldObject.name) {newObject.name = oldObject.name;}
  if(oldObject.id) {newObject.id = oldObject.id;}
  if(oldObject.className) {newObject.className = oldObject.className;}
  oldObject.parentNode.replaceChild(newObject,oldObject);
  newObject.select();
  return newObject;
}

function swapToText(date_type) {
    $('input[type="'+date_type+'"]').on("keydown", function(event) {
    if ((event.keyCode == 17) && (control_pressed != true)) {
      $(this).addClass("revert_date_to_text");
      changeInputType(this, "text");
      swapToDate(date_type);
      control_pressed = true;
    }
  })
}

function swapToDate(date_type) {
  $(".revert_date_to_text").on("keyup", function(event) {
    if ((event.keyCode == 17) && (control_pressed != false)) {
      $(this).removeClass("revert_date_to_text");
      if (date_type == 'datetime-local') {
        $(this).val($.format.date($(this).val().replace(/\//g,"-").replace("T"," ")+':00.000', "yyyy-MM-ddTHH:mm"));
      } else {
        $(this).val($.format.date($(this).val().replace(/\//g,"-"), "yyyy-MM-dd"));
      }
      changeInputType(this, date_type);
      swapToText(date_type);
      control_pressed = false;
    }
  })
}

$(function() {
  $.getScript('https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js');
  swapToText('date');
  swapToText('datetime-local');
});
+1

Source: https://habr.com/ru/post/1663986/


All Articles